动态SQL sp_executesql问题

时间:2010-08-26 18:25:10

标签: sql sql-server

我有以下查询:

DECLARE @sync_table_name nvarchar(500)
SET @sync_table_name = 'ContactTypes'

DECLARE @sync_batch_size bigint
SET @sync_batch_size = 2

DECLARE @sync_last_received_anchor timestamp
SET @sync_last_received_anchor = 1

DECLARE @sync_max_received_anchor timestamp
SET @sync_max_received_anchor = 18732866

DECLARE @sync_new_received_anchor timestamp
DECLARE @sync_batch_count int

DECLARE @sql NVARCHAR(500)
SET @sql = 'SELECT cast([version] as bigint) as [version], ROW_NUMBER() OVER(ORDER BY CAST([version] as BIGINT)) as RowNumber 
INTO #Temp FROM '+@sync_table_name+' WHERE [version] > @min AND [version] <= @max ORDER BY [version];  

SET @batchCountOUT = (SELECT COUNT(*) FROM #Temp) / @batchSize; 
IF ((SELECT COUNT(*) FROM #Temp) >= @batchSize) 
    SELECT @newAnchorOUT = #Temp.[version] FROM #Temp WHERE RowNumber = @batchSize;

IF ((SELECT COUNT(*) FROM #Temp) < @batchSize) 
    SELECT @newAnchorOUT = #Temp.[version] FROM #Temp WHERE RowNumber = (SELECT COUNT(*) FROM #Temp);

DROP TABLE #Temp'

DECLARE @sqlParam NVARCHAR(500)
SET @sqlParam = '@batchSize bigint, @min timestamp, @max timestamp, @newAnchorOUT timestamp OUTPUT, @batchCountOUT int OUTPUT'

EXECUTE sp_executesql @sql, @sqlParam, @batchSize = @sync_batch_size, @min = @sync_last_received_anchor, @max = @sync_max_received_anchor, @newAnchorOUT = @sync_new_received_anchor OUTPUT, @batchCountOUT = @sync_batch_count OUTPUT


            SELECT @sync_new_received_anchor, @sync_batch_count

总是在抱怨Msg 102,Level 15,State 1,Line 8 ')'附近的语法不正确。

但如果我删除第二个IF语句一切正常...... sp_executesql和IF语句是否有些奇怪

2 个答案:

答案 0 :(得分:5)

您的@sql值超过500个字符。增加可变大小。

答案 1 :(得分:2)

你的@sql = 716个字符。只需将其设为nvarchar(4000),这样就可以安全了