将参数作为字符串传递给动态SQL

时间:2014-12-30 01:37:25

标签: sql sql-server stored-procedures

考虑这个SQL语句:

DECLARE @SQLString          NVARCHAR(MAX)

SET @SQLString = '
DECLARE @CountryCode    varchar(3)
DECLARE @CountryName    varchar(60)

DECLARE AutoCursor CURSOR FOR

    SELECT DISTINCT 
        CountryCode, 
        CountryName 
    FROM Country

OPEN AutoCursor
FETCH FROM AutoCursor INTO @CountryCode, @CountryName

    WHILE @@fetch_status = 0
    BEGIN
            BEGIN TRAN

                EXEC SP_StoredProcedure_1
                    @ExtraWhereClause   = N'' AND CountryCode= ''''@CountryCode'''' '',
                    @Name               = @CountryName

            COMMIT TRAN                             
    FETCH Next FROM AutoCursor INTO @D_Nationcode, @C_Name
    END
CLOSE AutoCursor
DEALLOCATE AutoCursor;  
'
PRINT (@SQLString)
EXEC (@SQLString)

如何将@CountryCode作为参数传递给字符串?

@ExtraWhereClause = N'' AND CountryCode= ''' + @CountryCode + ''' ''似乎不起作用,因为@CountryCode已在动态SQL中使用。

3 个答案:

答案 0 :(得分:0)

我希望你能用更简单的Dynamic Sql

来做到这一点
Create table #temp (CountryCode int,
                      CountryName varchar(50))

declare @sql nvarchar(max)

set @sql = 'SELECT DISTINCT CountryCode, CountryName FROM ' + @TableName 

Insert into #temp
exec sp_executesql @sql

DECLARE @CountryCode VARCHAR(3)
DECLARE @CountryName VARCHAR(60)
DECLARE AutoCursor CURSOR FOR
  SELECT DISTINCT CountryCode,
                  CountryName
  FROM   #temp

OPEN AutoCursor

FETCH FROM AutoCursor INTO @CountryCode, @CountryName

WHILE @@FETCH_STATUS = 0
  BEGIN
      BEGIN TRAN

      EXEC Sp_storedprocedure_1
        @ExtraWhereClause = N'',
        @CountryCode= @CountryCode,
        @Name = @CountryName

      COMMIT TRAN

      FETCH Next FROM AutoCursor INTO @CountryCode, @CountryName
  END

CLOSE AutoCursor

DEALLOCATE AutoCursor 

答案 1 :(得分:0)

@ExtraWhereClause = N'' AND CountryCode= '''''' + @CountryCode+ ''''''  '',

得到它....我应该使用更多的撇号符号.... geez,我真的很难使用正确数量的撇号符号=(

答案 2 :(得分:0)

我在这里看不到任何需要动态sql的内容,但如果你真的真的想要你可以使用sp_executesql