我从sys表中获取了一组表名,并试图遍历它们以从中获取列,然后将其追加到动态SQL中。
我在语法上遇到问题。请帮我。 我试图将@tablename传递给select *语句,但它不喜欢它。请帮助我
DECLARE @col [VARCHAR](100);
DECLARE @TableCursor AS CURSOR;
SET
@TableCursor = CURSOR FOR
SELECT st.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES st
WHERE REPLACE(st.TABLE_NAME, 'TEST' + '_' + 'PIV' + '_', '') = 'Marketing_campaign'
AND st.TABLE_SCHEMA = 'DV';
DECLARE @Tablename VARCHAR(100);
OPEN @TableCursor;
FETCH NEXT FROM @TableCursor
INTO @Tablename;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @colCursor AS CURSOR;
SET @colCursor = CURSOR FOR
SELECT * FROM @Tablename; ****** this is where its complaining****
OPEN @colCursor;
FETCH NEXT FROM @colCursor
INTO @col;
WHILE @@FETCH_STATUS = 0
BEGIN
CLOSE @colCursor;
DEALLOCATE @colCursor;
END;
FETCH NEXT FROM @TableCursor
INTO @Tablename;
END;
CLOSE @TableCursor;
DEALLOCATE @TableCursor;
答案 0 :(得分:1)
您正在从@Tablename中进行选择 但在@Tablename的定义中,它是varchar(100) 您无法从varchar中选择
如果要选择,则需要从表中选择
看看这个,可能会有所帮助 Table name as variable