将新列添加到表的末尾后,我想立即将该列的值设置为等于表中另一列的值,仅使用后者的ORDINAL_POSITION
来自INFORMATION_SCHEMA.COLUMNS
表。这样,在将来不存在任何现有列的情况下,查询将不会被硬编码。
具体来说,我想将新列的值设置为等于previous
列的值(参考ORDINAL_POSITION
)。在SQL中,这意味着接近以下内容:
UPDATE DatabaseName.dbo.TableName
SET FSVAccessLvl = (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'DatabaseName'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'TableName'
GROUP BY ORDINAL_POSITION, COLUMN_NAME
HAVING ORDINAL_POSITION = MAX(ORDINAL_POSITION) - 1
)
有没有办法实现这个目标?对于包含 n 列的表,我基本上想说SET Col_n = Col_n-1
。有没有办法实现这个目标?欢迎任何帮助。
答案 0 :(得分:0)
实际上你的伪SQL看起来像这样:
UPDATE Table_Name
SET @New_Column = @Previous_Column
您需要做的就是从INFORMATION_SCHEMA
中选择一行,它将返回一个带有SQL语句的字符串并执行结果:
DECLARE @sql_update VARCHAR;
DECLARE @New_Column = 'Name_of_new_column';
SELECT
@sql_update = 'UPDATE Table_Name SET ' + @New_Column + ' = ' + @Previous_Column
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE c.ORDINAL_POSITION < ORDINAL_POSITION
AND c.TABLE_NAME = TABLE_NAME
AND c.TABLE_SCHEMA = TABLE_SCHEMA
AND c.COLUMN_NAME != @New_Column);
EXECUTE(@sql_update);