在select语句中设置变量

时间:2014-09-04 09:21:22

标签: sql sql-server-2008 tsql

SELECT   
    ft.id
    ,ft.date
    ,(SET @column = 
            CASE WHEN ft.a < 0 THEN 'Ok' END 
            CASE WHEN ft.b > 0 THEN 'NotOk' END
    ) AS 'Wrong sign in column ' + @column
FROM dbo.table AS ft

为什么这不起作用?我收到语法错误,我看不到它..我想根据条件构建选定的列。

  

Msg 156,Level 15,State 1,Line 8
  关键字“SET”附近的语法不正确。

     

Msg 156,Level 15,State 1,Line 10
  关键字'CASE'附近的语法不正确。

2 个答案:

答案 0 :(得分:1)

你做错了......试试:

SELECT  ft.nBranchId
      , ft.tmDate
      ,'Wrong sign in column ' +
        CASE WHEN ft.fDeposits < 0 THEN 'fDeposits'
             WHEN ft.fWithdrawals > 0 THEN 'fWithdrawals'
             WHEN ft.fPerformanceFee > 0 THEN 'fPerformanceFee'
             WHEN ft.fFixedFee > 0 THEN 'fFixedFee'
             WHEN ft.fDividend > 0 THEN 'fDividend'
             WHEN ft.fReinvestment < 0 THEN 'fReinvestment'
             WHEN ft.fThresholdRate < 0 THEN 'fThresholdRate'
             WHEN ft.fPerfFeeCumulated > 0 THEN 'fPerfFeeCumulated'
        END
FROM dbo.FundTransactions AS ft

答案 1 :(得分:1)

您可以直接使用变量的内容,而不是在查询中设置变量。 以下查询将为您提供所需的结果。

此外,如果不在sql中声明变量,则无法使用该变量。

SELECT  ft.nBranchId
      , ft.tmDate
      ,'Wrong sign in column ' +
        CASE WHEN ft.fDeposits < 0 THEN 'fDeposits'
             WHEN ft.fWithdrawals > 0 THEN 'fWithdrawals'
             WHEN ft.fPerformanceFee > 0 THEN 'fPerformanceFee'
             WHEN ft.fFixedFee > 0 THEN 'fFixedFee'
             WHEN ft.fDividend > 0 THEN 'fDividend'
             WHEN ft.fReinvestment < 0 THEN 'fReinvestment'
             WHEN ft.fThresholdRate < 0 THEN 'fThresholdRate'
             WHEN ft.fPerfFeeCumulated > 0 THEN 'fPerfFeeCumulated'
        END
      as ColumnName
FROM dbo.FundTransactions AS ft