2

在下面,如果我尝试在 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

以下代码是否有问题会导致打印语句不起作用?

    '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'
4

2 回答 2

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 语句工作正常。

于 2013-11-07T17:00:34.163 回答
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 
于 2013-11-07T14:14:07.130 回答