在下面,如果我尝试在BEGIN语句之后放置一个打印它不起作用,当我删除BEGIN-END语句中的所有内容并放置一个打印它确实有效;
SET @SQL = 'IF (((SELECT fldLT FROM #zArray) = ''p'') OR ((SELECT fldMF FROM #zArray) <> -1))
BEGIN
SET @X = '+@Z+' * ((SELECT fldLF FROM #zArray) / 100))
IF (CAST((SELECT fldMF FROM #zArray) AS FLOAT) > '+@X+')
BEGIN
SET @X = (CAST((SELECT fldMF FROM #zArray) AS FLOAT))
END
END'
EXEC sp_executesql @SQL, N'@X NVARCHAR(50),@Z NVARCHAR(50)', @X, @Z
以下代码是否有问题导致print语句不起作用?
'SET @X = '+@Z+' * ((SELECT fldLF FROM #zArray) / 100))
IF (CAST((SELECT fldMF FROM #zArray) AS FLOAT) > '+@X+')
BEGIN
SET @X = (CAST((SELECT fldMF FROM #zArray) AS FLOAT))
END'
答案 0 :(得分:2)
我不明白为什么你要连接你的参数而你又在sp_executesql
的程序中再次使用它们。
我修改了一些查询,删除了参数的串联并使用REPLACE函数,用您的参数替换占位符:
DECLARE @X NVARCHAR(50) = '123'
DECLARE @Z NVARCHAR(50) = '123'
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 'IF (((SELECT fldLT FROM #zArray) = ''p'') OR ((SELECT fldMF FROM #zArray) <> -1))
BEGIN
SET @paramX = @paramZ * ((SELECT fldLF FROM #zArray) / 100))
IF (CAST((SELECT fldMF FROM #zArray) AS FLOAT) > @paramX)
BEGIN
SET @paramX = (CAST((SELECT fldMF FROM #zArray) AS FLOAT))
END
END'
SET @SQL = REPLACE(@SQL,'@paramX',@X)
SET @SQL = REPLACE(@SQL,'@paramZ',@Z)
PRINT @SQL
EXEC sp_executesql @SQL
对我来说,PRINT声明工作正常。
答案 1 :(得分:0)
您需要将SQL语句作为字符串传递,而不是在动态sql中使用的变量
DECLARE @Xr NVARCHAR(50) = '1000351' DECLARE @Zr NVARCHAR(50) = '46546321'
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 'IF (((SELECT fldLT FROM #zArray) = ''p'') OR ((SELECT fldMF FROM #zArray) <> -1))
BEGIN
SET @X = @Z * ((SELECT fldLF FROM #zArray) / 100))
IF (CAST((SELECT fldMF FROM #zArray) AS FLOAT) > @X)
BEGIN
SET @X = (CAST((SELECT fldMF FROM #zArray) AS FLOAT))
END
END '
PRINT @SQL
EXEC sp_executesql @SQL,
N'@X NVARCHAR(50),@Z NVARCHAR(50)',
@X = @Xr,
@Z = @Zr
打印结果
IF (((SELECT fldLT FROM #zArray) = 'p') OR ((SELECT fldMF FROM #zArray) <> -1))
BEGIN
SET @X = 46546321 * ((SELECT fldLF FROM #zArray) / 100))
IF (CAST((SELECT fldMF FROM #zArray) AS FLOAT) > 1000351)
BEGIN
SET @X = (CAST((SELECT fldMF FROM #zArray) AS FLOAT))
END
END