我在 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