知道为什么我的@ProductNumber游标变量在动态语句中使用时不起作用?它说“必须声明标量变量”。但这是一个游标变量。但是,当我使用它时,它不是动态的,它可行。感谢。
DECLARE @TargetDB NVARCHAR(50)
DECLARE @SourceDB NVARCHAR(50)
DECLARE @DateEffectiveFrom datetime
DECLARE @InsertRecords NVARCHAR(1000)
SET @TargetDB = 'MySSISDb'
SET @SourceDB = 'MySSISDb2'
SET @DateEffectiveFrom = '2013-12-29'
Declare @ProductNumber INT;
DECLARE @SqlDb NVARCHAR(Max)
DECLARE Cur1 CURSOR FOR SELECT CAST(@SqlDb AS NVARCHAR(MAX))
SET @SqlDb = 'SELECT ProductNumber From '+@SourceDB+'.dbo.Item (NOLOCK)
WHERE NOT EXISTS (SELECT 1 FROM '+@TargetDB+'.dbo.Item2
WHERE ProductNumber = '+@SourceDB+'.dbo.Item.ProductNumber)'
EXEC sp_executesql @SqlDb
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ProductNumber;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @InsertRecords = 'INSERT INTO ' + @TargetDB + '.dbo.Item2(
ProductNumber, ProductName, ListPrice, BirthDate)
SELECT ProductNumber, ProductName,
ListPrice, ''' + CONVERT(nvarchar(25),@DateEffectiveFrom,120) + '''
FROM ' + @SourceDB + '.dbo.Item
WHERE ' + @SourceDB + '.dbo.Item.ProductNumber = @ProductNumber'
--WHERE ' + @SourceDB + '.dbo.Item.ProductNumber = @ProductNumber
--(this is where the problem)
EXEC sp_executesql @InsetRecords
FETCH NEXT FROM Cur1 INTO @ProductNumber;
END
CLOSE Cur1;
DEALLOCATE Cur1;
答案 0 :(得分:1)
将光标的声明转换为SQLDb变量。在SQL Server中,至少在执行@SQLDb后可以访问游标名称“Cur1”。另外,我已经将@ProductNumber的使用移到了文字字符串之外,并在游标循环中修改了第二个EXEC语句的拼写错误(@InsetRecords to @InsertRecords)。
DECLARE @TargetDB NVARCHAR(50)
DECLARE @SourceDB NVARCHAR(50)
DECLARE @DateEffectiveFrom datetime
DECLARE @InsertRecords NVARCHAR(1000)
SET @TargetDB = 'MySSISDb'
SET @SourceDB = 'MySSISDb2'
SET @DateEffectiveFrom = '2013-12-29'
Declare @ProductNumber INT;
DECLARE @SqlDb NVARCHAR(Max)
SET @SqlDb = '
DECLARE Cur1 CURSOR FOR
SELECT ProductNumber
From '+@SourceDB+'.dbo.Item (NOLOCK)
WHERE NOT EXISTS (
SELECT 1
FROM '+@TargetDB+'.dbo.Item2
WHERE ProductNumber = '+@SourceDB+'.dbo.Item.ProductNumber)'
EXEC sp_executesql @SqlDb
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ProductNumber;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @InsertRecords = 'INSERT INTO ' + @TargetDB + '.dbo.Item2(
ProductNumber, ProductName, ListPrice, BirthDate)
SELECT ProductNumber, ProductName,
ListPrice, ''' + CONVERT(nvarchar(25),@DateEffectiveFrom,120) + '''
FROM ' + @SourceDB + '.dbo.Item
WHERE ' + @SourceDB + '.dbo.Item.ProductNumber = ' + CONVERT(nvarchar(max), @ProductNumber)
EXEC sp_executesql @InsertRecords
FETCH NEXT FROM Cur1 INTO @ProductNumber;
END
CLOSE Cur1;
DEALLOCATE Cur1;