2017-04-26 95 views
1

下午好朋友。我有下面的語法,我很難理解實際問題。 SSMS給我提供了'Select'附近錯誤的語法錯誤 - 並且它將整個SQL字符串反饋給我。動態SQL拋出錯誤語法

有人可以在這裏指出問題是什麼以及如何補救?

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


SET @rep = CHAR(39)+CHAR(39)[email protected]+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 ('[email protected]+') 
       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

很多報價。共享生成的SQL –

+0

@JohnCappelletti - 請參閱編輯 - 並感謝您 –

回答

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 (|'[email protected]+'|) 
    and jbhiredate BETWEEN |'+ @startdate + '| AND |' + @enddate +'|' 

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

PRINT @SQL