我似乎无法在动态执行的@tblName
语句中将SELECT
变量添加为别名列 - 下面的vanTbl - SQL不断抛出错误
列名无效
也许这是一些范围问题?任何建议非常感谢。如果在某处已经解决过,请提前道歉,这太模糊了等等。
DECLARE @tblName varchar(64)
DECLARE @sqlCommand nvarchar(1000)
DECLARE cursor1 CURSOR FOR
(SELECT DISTINCT t1.TABLE_NAME
FROM
(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (COLUMN_NAME = 'x_SECTION'
OR COLUMN_NAME = 'x_TABLE')
) t1
GROUP BY t1.TABLE_NAME)
OPEN cursor1
FETCH NEXT FROM cursor1 INTO @tblName
SET @sqlCommand = 'SELECT DISTINCT ' +@tblName+ ' as vanTbl,
SECTION, SHAPE, TABLENAME, x_SECTION, x_TABLE FROM ' +@tblName + '
WHERE x_SECTION <> '' '''
EXEC(@sqlCommand)
CLOSE cursor1
DEALLOCATE cursor1
答案 0 :(得分:0)
tblName应该用额外的引号括起来,因为它是一个字符串值:
'SELECT DISTINCT ''' +@tblName+ ''' as vanTbl,
这将导致:
'SELECT DISTINCT 'TBL_NAME' as vanTbl,
光标中没有循环似乎存在问题,但这可能是另一个问题。你应该看一些游标示例。