如果语句符合SQL,则选择特定项

时间:2015-09-24 11:25:18

标签: sql sql-server sql-server-2008-r2

存在类似的内容:

@isParamSet int
SELECT
CASE
WHEN @isParamSet=1 THEN Name, Surname
END
telNumber
FROM DETAILS

这当然是一个存储过程。

2 个答案:

答案 0 :(得分:2)

如果SQL Server

IF @isParamSet = 1
  SELECT
    Name,
    Surname,
    telNumber
  FROM DETAILS
ELSE
  SELECT
    telNumber
  FROM DETAILS

您还可以使用Dynamic-SQL构建列列表。

DECLARE @sql NVARCHAR(MAX) = 
      N'SELECT
        {other}
        telNumber
      FROM DETAILS';

SELECT @sql = REPLACE(@sql, '{other}', CASE
                                       WHEN @isParamSet = 1 THEN 'Name, Surname, '
                                       ELSE ''
                                       END );

EXEC [dbo].[sp_executesql]
     @sql;

修改

您可以将参数传递给Dynamic-SQL,如

DECLARE @sql NVARCHAR(MAX) = 
      N'SELECT
        {other}
        telNumber
      FROM DETAILS
      WHERE country = @country';

SELECT @sql = REPLACE(@sql, '{other}', CASE
                                       WHEN @isParamSet = 1 THEN 'Name, Surname, '
                                       ELSE ''
                                       END );

EXEC [dbo].[sp_executesql]
     @sql
     ,N'@country NVARCHAR(100)' -- pass correct type
     ,@country;

答案 1 :(得分:0)

试试这个

declare @sql nvarchar(max)

set @sql  = 'SELECT ' +
CASE
WHEN @isParamSet=1 THEN 'Name, Surname,' else ''
END + '
telNumber
FROM DETAILS'

Exec sp_executesql @sql