在SQL Server中使用单个查询更新多个表

时间:2016-04-09 17:53:39

标签: sql-server

在我的数据库中有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

但我不知道如何使用单个查询更新这些表。

请尽可能帮助我。

1 个答案:

答案 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

Here is good article for Dynamic SQL