动态SQL引发不正确的语法

时间:2017-04-26 17:28:37

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

下午好朋友。我有以下语法,我不知道实际问题是什么。 SSMS向我显示“'选择'附近的错误语法错误 - 它将整个SQL字符串反刍了。

有人可以指出问题是什么以及如何解决它?

    Declare @rep varchar(max) = 'Habib', @startdate varchar(100) = '01/01/2017', @enddate varchar(100) = '03/31/2017'


SET @rep = CHAR(39)+CHAR(39)+@rep+CHAR(39)+CHAR(39)

Declare @sql nvarchar(4000) = 'Select * FROM OPENQUERY(sumSol,''Select 
        representative repName
        ,hiredate hiredate
FROM alpha ac
WHERE smellogram IN (''''1'''',''''3'''',''''4'''',''''5'''',''''6'''') 
AND id IN (Select id from frank)
               AND ((NOT ((holdingstatus = ''''13''''))))
               AND representative IN ('+@rep+')
               AND jbhiredate BETWEEN ('+ CHAR(39) + CHAR(39)
                               + CAST(@startdate AS NVARCHAR(500)) + CHAR(39) + CHAR(39) + N')
                               AND (' + CHAR(39) + CHAR(39) + CAST(@enddate AS NVARCHAR(500)) + CHAR(39) + CHAR(39) + N' '')'


PRINT @SQL
EXEC sp_ExecuteSQL @SQL

我得到的错误是

  

字符串

后的未闭合引号

修改
这是生成的SQL

    Select * FROM OPENQUERY(sumSol,''Select 
        representative repName
        ,hiredate hiredate
FROM alpha ac
WHERE smellogram IN (''1'',''3'',''4'',''5'',''6'')
AND id IN (Select id from frank)
               AND ((NOT ((holdingstatus = ''13''))))
               AND representative IN ('Habib')
               AND jbhiredate BETWEEN (''01/01/2017'')  AND (''03/31/2017'')')

1 个答案:

答案 0 :(得分:0)

很容易迷失所有的双引号。这就是为什么我经常使用PIPE来表示单引号,然后执行简单的替换。

未经测试

Declare @rep varchar(max) = 'Habib', @startdate varchar(100) = '01/01/2017', @enddate varchar(100) = '03/31/2017'

Declare @sql nvarchar(4000) = '
Select representative repName
      ,hiredate hiredate
 From  alpha ac
 Where smellogram IN (|1|,|3|,|4|,|5|,|6|) 
   and id IN (Select id from frank)
   and ((NOT ((holdingstatus = |13|))))
   and representative IN (|'+@rep+'|)
   and jbhiredate BETWEEN |'+ @startdate + '| AND |' + @enddate +'|'

Select @SQL = 'Select * FROM OPENQUERY(sumSol,''' + replace(@SQL,'|','''''') + ''')'

PRINT @SQL