考虑这个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中使用。
答案 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