在我的数据库中有85个表,大约62个表有一个共同的列ArchiveID
。我有其他表EDSArchiveHistory
CREATE TABLE [dbo].[EDSArchiveHistory]
(
[ArchiveID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[ArchiveDate] [datetime] NOT NULL,
[ArchiveName] [nvarchar](200) NOT NULL
)
当我将任何记录插入EDSArchiveHistor
时,我想获取插入记录的ArchiveID
并更新所有具有ArchiveID
列的表。
基本上我编写查询来查找具有ArchiveID
列
SELECT NAME
FROM SYS.TABLES
WHERE OBJECT_ID IN (SELECT OBJECT_ID AS NAME
FROM SYS.COLUMNS
WHERE NAME LIKE '%ARCHIVEID%')
AND NAME <> 'EDSARCHIVEHISTORY'
ORDER BY NAME
但我不知道如何使用单个查询更新这些表。
请尽可能帮助我。
答案 0 :(得分:0)
通过SQL Dynamic Query可以通过单个查询更新多个表。
ALTER PROCEDURE sp_ArchiveManagment
@paramARCHIVEID INT
AS
DECLARE @TempTableList TABLE (ID INT IDENTITY(1,1),NAME NVARCHAR(300))
BEGIN
INSERT INTO @TempTableList (NAME) (
SELECT NAME FROM SYS.TABLES
WHERE OBJECT_ID IN (
SELECT OBJECT_ID AS NAME FROM SYS.COLUMNS
WHERE NAME LIKE '%ARCHIVEID%'
) AND
NAME <> 'EDSARCHIVEHISTORY')
DECLARE @REC_ID AS INT
SET @REC_ID = 1
DECLARE @SQLQUERY AS NVARCHAR(MAX)
WHILE (@REC_ID <= (SELECT COUNT(*) FROM @TempTableList))
BEGIN
DECLARE @TblName VARCHAR (200)
SET @TblName=(SELECT NAME FROM @TempTableList WHERE ID=@REC_ID)
SET @SQLQUERY= 'UPDATE '+@TblName+' SET ARCHIVEID ='+CAST(@paramARCHIVEID AS VARCHAR(4))+' WHERE ARCHIVEID IS NULL'
EXECUTE(@SQLQuery)
SET @REC_ID= @REC_ID + 1
END
END