SQL Server动态SQL语法

时间:2014-07-23 12:39:57

标签: sql sql-server

由于具有变量表名,我试图使用动态sql查询。我无法解决在@ParentItem的Where子句中使用的正确语法。我要么得到一个消息,我必须在h附近声明标量变量或不正确的语法,其中@ParentItem = N'123-123h'。我尝试过各种版本的单引号但没有成功。

EXEC(
'SELECT j.job
 FROM Malt'+@Number+'
 RIGHT Join job j on BOMID LIKE ''%''+ j.job
 WHERE BOMID IN (Select ''.'' + j.job                   
FROM job j
WHERE j.item = '+@ParentItem+' AND j.type = ''S''')
GROUP BY j.job') 

1 个答案:

答案 0 :(得分:0)

似乎错过了S之后的右括号和围绕parentItem的引号;试试这个:

EXEC(
'SELECT j.job
 FROM Malt'+@Number+'
 RIGHT Join job j on BOMID LIKE ''%''+ j.job
 WHERE BOMID IN (Select ''.'' + j.job                   
FROM job j
WHERE j.item = ''' + @ParentItem +''' AND j.type = ''S'') GROUP BY j.job')
)