1

我在 T-SQL 中有以下代码,它从游标中读取表名。

但是我对WITH语句中的范围表名称变量有疑问。

当我明确设置dbo.@sys_name为同义词名称时,我可以运行此代码,dbo.mysysnonym但是当我将其作为变量名称时,dbo.@syn_name它不起作用。

 -- drop duplicates records from synonyms
 DECLARE @syn_name varchar(50)

 DECLARE s_cursor CURSOR FOR  
     SELECT name 
     FROM sys.synonyms  
     WHERE  base_object_name LIKE 'xyz%'

 OPEN s_cursor;

 FETCH NEXT FROM s_cursor INTO @syn_name;

 WHILE @@FETCH_STATUS = 0
 BEGIN

     FETCH NEXT FROM s_cursor INTO @syn_name;

     WITH  dedupTable AS 
     (
         SELECT 
             sys_id, 
             row_number() OVER (PARTITION BY sys_id ORDER BY sys_id) AS nr
         FROM 
             dbo.@syn_name
     )
     DELETE  FROM dedupTable
     WHERE nr > 1
END;

CLOSE s_cursor
DEALLOCATE s_cursor
4

1 回答 1

2

据我所知,您不能将变量用作表名,因此dbo.@syn_name不能在FROM子句中使用。相反,您将不得不使用Dynamic SQL

就像是:

...
FETCH NEXT FROM s_cursor INTO @syn_name;
DECLARE @sql nvarchar(4000)

SET @sql = N'
    WITH  dedupTable
    AS ( 
       SELECT sys_id, row_number() 
       OVER ( PARTITION BY sys_id ORDER BY sys_id  ) AS nr
       FROM dbo.' + @syn_name + '
    )
    DELETE  FROM dedupTable
    WHERE   nr > 1'

EXEC sp_executesql @sql
于 2012-12-17T21:12:46.507 回答