我有一个动态sql,其中我使用case with variable但它给出了错误。
这是剪辑。
DECLARE @SQL VARCHAR(MAX)
DECLARE @isrepaired INT
SET @isrepaired=1
SET @SQL=@SQL+'SELECT *
FROM (SELECT Row_number()
OVER (
ORDER BY [bbajobs].[customername] ) AS
RowNumber,
[bbajobs].[jid],
ourfeedback.rating,
ourfeedback.adddates as [Add Dates]
,Repaired=
case '+CAST(@isrepaired as varchar)+' when 1 then ''Yes''
case '+CAST(@isrepaired as varchar)+' when 0 then ''No''
END
FROM dbo.bbajobs '
我在运行时发送isrepaired的值。我们不能这样写这样的声明吗?请指导我在哪里修理。感谢
动态sql是我的要求所以指导我如何在动态sql
中做到这一点DECLARE @SQL VARCHAR(MAX)
DECLARE @isrepaired INT
SET @isrepaired=1
SET @SQL=@SQL+'SELECT *
FROM (SELECT Row_number()
OVER (
ORDER BY [bbajobs].[customername] ) AS
RowNumber,
[bbajobs].[jid],
ourfeedback.rating,
ourfeedback.adddates as [Add Dates]
,Repaired=
case '+CAST(@isrepaired as varchar)+' when 1 then ''Yes''
'+CAST(@isrepaired as varchar)+' when 0 then ''No''
END
FROM dbo.bbajobs '
我的动态SQL看起来像
SELECT *
FROM (SELECT Row_number()
OVER (
ORDER BY [bbajobs].[customername] ) AS
RowNumber,
[bbajobs].[jid],
ourfeedback.rating,
ourfeedback.adddates as [Add Dates]
,Repaired=
case 1 when 1 then ''Yes''
when 0 then ''No''
END
FROM dbo.bbajobs '
答案 0 :(得分:0)
这里没有明显的动态SQL需求。只需使用
SELECT *
FROM (SELECT Row_number() OVER ( ORDER BY [bbajobs].[customername] ) AS RowNumber,
[bbajobs].[jid],
ourfeedback.rating,
ourfeedback.adddates AS [Add Dates],
Repaired= CASE @isrepaired
WHEN 1 THEN 'Yes'
WHEN 0 THEN 'No'
END
FROM dbo.bbajobs) AS T
如果由于未显示的原因确实需要动态SQL,那么至少应首先使用有效的非动态查询,然后将其转换。
您缺少派生表的表别名,case ... case ... end
无效。
查询的语义看起来很奇怪。为什么修复状态仅来自所有行的@isrepaired
变量?
答案 1 :(得分:0)
你的语法错了。你有两个案例。它应该是什么时候。
http://technet.microsoft.com/en-us/library/ms181765.aspx
Searched CASE expression:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
此外,使用此指令可以查看在XML窗口中动态生成的代码。剪切并粘贴到另一个窗口进行调试。这样你就可以验证语法。
-- Cool instruction ?
SELECT @SQL as [processing-instruction(TSQL)] FOR XML PATH