c# – 如何在SQL中按列名检查单元格是否为空?

我试图在SQL中构建存储过程.我有以下语法:CREATE PROCEDURE [dbo].[getAllCitizens]@NoInfo as nvarchar(50) = No contact information inserted.ASBEGINSET NOCOUNT ON;IF ctznPhone != nullBEGINSELECT ctzn...

我试图在SQL中构建存储过程.

我有以下语法:

CREATE PROCEDURE [dbo].[getAllCitizens]
    @NoInfo as nvarchar(50) = "No contact information inserted."
AS
BEGIN
    SET NOCOUNT ON;
    IF ctznPhone != null
        BEGIN
            SELECT ctznTz, ctznLname, ctznFname, ctznPhone
            FROM tblCitizens
            Where ctznLivestat=1
        END
    ELSE
        BEGIN
            IF ctznEml != null
                BEGIN
                SELECT ctznTz, ctznLname, ctznFname, ctznEml
                FROM tblCitizens
                Where ctznLivestat=1
                END
            ELSE
                BEGIN
                    SELECT ctznTz, ctznLname, ctznFname, @NoInfo
                    FROM tblCitizens
                    Where ctznLivestat=1
                END
        END
END

如何告诉ctznPhone和ctznEml列在哪个表中的过程?

我尝试了dbo.tablename.columname以及使用()和[]的各种尝试但它似乎不起作用.

最终,此过程将由C#datareader调用.
我要做的是构建一个过程,当被调用时,将从一行返回所选单元格,具体取决于特定单元格中的信息:

>如果ctznPhone不为null,那么我想得到它.
>如果它为null,我想要获得ctznEml.
>如果THAT也为空,我想收到一条消息,表明没有联系信息可用(我在@NoInfo中放置的字符串).

我是以正确的方式来做这件事的吗?

解决方法:

你可以使用COALESCE:

COALESCE ( expression [ ,…n ] )

Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

CREATE PROCEDURE [dbo].[getAllCitizens]
    @NoInfo as nvarchar(50) = "No contact information inserted."
AS
BEGIN
  SET NOCOUNT ON;

  SELECT ctznTz, ctznLname, ctznFname,
         COALESCE(ctznPhone, ctznEml, @NoInfo) AS contactInfo
  FROM tblCitizens
  WHERE ctznLivestat=1;

END

本文标题为:c# – 如何在SQL中按列名检查单元格是否为空?

基础教程推荐