我需要更新包含它的所有表中的id_ciudad
列,可能使用脚本。此外,该脚本将在几个大型数据库中执行。问题是,某些表对于所有数据库都不相同,但它们确实(当然)确实存在这一列。
在互联网上查看我可以构建这个脚本,但它不起作用。使用此脚本,我获取所有带有id_ciudad
的表并迭代它,但我收到此错误
列名'id_ciudad'无效
有没有人可以帮助我? :d
DECLARE @tabsConCiudad AS TABLE (id_table int, table_name VARCHAR(75) )
DECLARE @id_table as int
DECLARE @table_name as VARCHAR(75)
-- It obtain correctly the tables with id_ciudad column
INSERT INTO @tabsConCiudad (id_table, table_name)
SELECT object_id, name
FROM sys.tables
WHERE object_id IN (SELECT object_id
FROM sys.columns
WHERE name LIKE 'id_ciudad')
DECLARE _CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
SELECT id_table
FROM @tabsConCiudad
OPEN _CURSOR
--It iterate the obtained tables correctly
FETCH NEXT FROM _CURSOR INTO @id_table
WHILE @@FETCH_STATUS = 0
BEGIN
--This part is the bad part, in the update
UPDATE tab
SET tab.[id_ciudad] = ciudades.id_ciudad
FROM [sys].[dm_db_index_operational_stats]( Null, @id_table, Null, Null ) tab, [cw_core].[ciudades] ciudades
WHERE tab.[id_ciudad] = ciudades.old_id_HO
FETCH NEXT FROM _CURSOR INTO @id_table
END
CLOSE _CURSOR
DEALLOCATE _CURSOR
答案 0 :(得分:0)
OP解决方案。
要解决此问题,请将EXECUTE与要执行的查询字符串一起使用。换句话说,更新包含名为"city_id"
的列的表的值。
DECLARE @ciudadDefecto as int
DECLARE @tabsConCiudad AS TABLE (id_table int, table_name VARCHAR(75) )
DECLARE @table_name as VARCHAR(75)
DECLARE @table_complete_name as VARCHAR(175)
DECLARE @queryString as VARCHAR(1000)
insert into @tabsConCiudad (id_table, table_name)
select object_id, name
from sys.tables
where object_id in
(select object_id
from sys.columns
where name like 'id_ciudad_registro')
DECLARE _CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR SELECT table_name FROM @tabsConCiudad
OPEN _CURSOR
FETCH NEXT FROM _CURSOR INTO @table_name
WHILE @@FETCH_STATUS = 0 BEGIN
Set @table_complete_name = CONCAT ( '[cw_core].[', @table_name, ']')
print CONCAT('Ejecutando: actualizacion a tabla ', @table_complete_name)
set @queryString = CONCAT ( 'Update tab ', '')
set @queryString = CONCAT ( @queryString, ' set tab.id_ciudad_registro = ciudades.id_ciudad ')
set @queryString = CONCAT ( @queryString, ' from ', @table_complete_name, ' tab, [cw_core].[ciudades] ciudades ' )
set @queryString = CONCAT ( @queryString, ' where tab.id_ciudad_registro = ciudades.old_id_HO' )
EXECUTE(@queryString)
FETCH NEXT FROM _CURSOR INTO @table_name
END
CLOSE _CURSOR DEALLOCATE _CURSOR