如果存在则更新XML列或插入引用表中的新行

时间:2016-09-22 10:19:03

标签: sql sql-server xml

如果将数据存在于父表中,则根据引用id更新XML列上的子表,其他方式插入行。

CREATE TABLE Person
(
 PersonId INT CONSTRAINT PK_Person_PersonId PRIMARY KEY,
 Name VARCHAR(50),
 SubMittedDate DATETIME,
 SubmittedBy INT,
 RejectedDate DATETIME,
 RejectedBy INT
)

INSERT INTO Person VALUES(1, 'Sai', GETDATE(),1,null,null)

CREATE TABLE PersonXML
(
 PersonXMLId INT IDENTITY(1,1) CONSTRAINT PK_PersonXML_PersonId PRIMARY KEY,
 PersonId INT CONSTRAINT FK_PersonXML_Person FOREIGN KEY REFERENCES Person(PersonId),
 Name VARCHAR(50),
 PersonHistory XML
)

INSERT INTO PersonXML(PersonId,Name,PersonHistory )
SELECT PersonId
      ,Name
      ,(SELECT PersonId             
            ,Name
            ,SubMittedDate
            ,SubmittedBy
            ,ISNULL(RejectedDate,0) AS RejectedDate
            ,ISNULL(RejectedBy, 0)  AS RejectedBy
            FROM Person FOR XML PATH('PersonHistory') )
FROM Person 

SELECT * FROM Person
SELECT * FROM  PersonXML

每当我在RejectedDate,RejectedBy Column中更新人员表时,那些更改必须自动反映在PersonH​​istory列的PersonXML表中,任何人都可以找到我实现它的方法。

UPDATE Person SET RejectedDate = GETDATE(), RejectedBy= 100 WHERE PersonId = 1 

1 个答案:

答案 0 :(得分:0)

DECLARE @PersonId int,@RejectedDate datetime,@RejectedBy int            
SET @PersonId=1
SET @RejectedDate=Getdate()+1
SET @RejectedBy=105
CREATE TABLE Person
(
 PersonId INT CONSTRAINT PK_Person_PersonId PRIMARY KEY,
 Name VARCHAR(50),
 SubMittedDate DATETIME,
 SubmittedBy INT,
 RejectedDate DATETIME,
 RejectedBy INT
)

INSERT INTO Person VALUES(1, 'Sai', GETDATE(),1,null,null)

CREATE TABLE PersonXML
(
 PersonXMLId INT IDENTITY(1,1) CONSTRAINT PK_PersonXML_PersonId PRIMARY KEY,
 PersonId INT CONSTRAINT FK_PersonXML_Person FOREIGN KEY REFERENCES Person(PersonId),
 Name VARCHAR(50),
 PersonHistory XML
)

INSERT INTO PersonXML(PersonId,Name,PersonHistory )
SELECT PersonId
      ,Name
      ,(SELECT PersonId             
            ,Name
            ,SubMittedDate
            ,SubmittedBy
            ,ISNULL(RejectedDate,0) AS RejectedDate
            ,ISNULL(RejectedBy, 0)  AS RejectedBy
            FROM Person FOR XML PATH('PersonHistory') )
FROM Person 

IF Exists(SELECT * FROM Person WHERE PersonId=@PersonId)  
BEGIN  
 UPDATE Person  
SET  
 RejectedDate =@RejectedDate ,RejectedBy=@RejectedBy
WHERE PersonId=@PersonId  
    UPDATE PersonXML  
    SET PersonHistory= 
    (SELECT PersonId             
            ,Name
            ,SubMittedDate
            ,SubmittedBy
            ,ISNULL(RejectedDate,@RejectedDate) AS RejectedDate
            ,ISNULL(RejectedBy,@RejectedBy)  AS RejectedBy
            FROM Person FOR XML PATH('PersonHistory')  )WHERE PersonId=@PersonId 
END
   ELSE  
     BEGIN  
          INSERT INTO Person 
          Select @PersonId,'', GETDATE(),1,@RejectedDate,@RejectedBy

     END  
SELECT * FROM Person
SELECT * FROM  PersonXML