使用引用ID编辑和更新记录

时间:2015-05-04 06:55:44

标签: sql .net sql-server

我在一个字段名称中有多个记录的表注释...使用我的aspx代码,注释列中的数据被插入三行中,其中包含不同的需求,但字段注释将保持不变 检索不同我使用此查询

SELECT distinct (
                 select top 1 requirementcommentid 
                 from Requirementcomment 
                 where requirementcomment=rc.requirementcomment 
                 and fcr.SectionID in(
                                      SELECT sectionid 
                                      FROM [dbo].udfGetSectionID_allComYear(2151)
                                      ) 
                 AND fcr.FirmID = 20057
                 ), 
       rc.IsRejected, 
       fcr.SectionID,
       rc.UserID,
       rc.RequirementComment,
       convert(varchar(25), dateadd(hour, -5, rc.InsertDate),101) as InsertDate,
       Department.DeptName,
       FirmUser.DepartmentID,
       rc.FirmComplianceYearID 
FROM RequirementComment rc 
INNER JOIN FirmComplianceRequirement fcr ON fcr.FirmComplianceRequirementID = rc.FirmComplianceRequirementID 
INNER JOIN FirmUser ON FirmUser.FirmUserID =rc.UserID 
INNER JOIN Department ON Department.DeptID = FirmUser.DepartmentID WHERE rc.IsRejected = 1 
AND fcr.SectionID in(SELECT sectionid FROM [dbo].udfGetSectionID_allComYear (2151))
AND fcr.FirmID = 20057 AND rc.RequirementComment!='' 

如果我想编辑这个不同的评论并更新它。我可以这样做...因为只有一个评论行被编辑剩下的两行值在字段评论中保持不变...!

如果我点击编辑并仅更新单个记录

,我希望自动更新剩余数据

1 个答案:

答案 0 :(得分:0)

如果在存储时无法通过过程解决此问题,或者在.NET中,请考虑使用触发器。我做了一个通用的例子,因为你的示例代码有点复杂:)

CREATE TABLE TMP_TriggerTable
(
    ID INT IDENTITY(1,1) PRIMARY KEY
    , ID2 INT NOT NULL
    , Comment VARCHAR(255) NOT NULL
)

GO

INSERT INTO TMP_TriggerTable
SELECT 1, 'asd'
UNION ALL
SELECT 1, 'asd'
UNION ALL
SELECT 1, 'asd'
UNION ALL
SELECT 2, 'asd'
UNION ALL
SELECT 2, 'asd'
UNION ALL
SELECT 2, 'asd'

GO


CREATE TRIGGER TRG_TMP_TriggerTable ON TMP_TriggerTable
AFTER UPDATE
AS
BEGIN

    WITH InsertedIDPriority AS
    (
        --Handle if more than one related comment was updated
        SELECT Prio = ROW_NUMBER() OVER (PARTITION BY ID2 ORDER BY ID)
        , ID
        , ID2
        , Comment 
        FROM INSERTED
    )
    UPDATE t SET Comment = i.Comment FROM TMP_TriggerTable t
    JOIN InsertedIDPriority i ON 
    t.ID2 = i.ID2 --Select all related comments
    AND t.ID != i.ID2 --No need to update main column two times
    AND i.Prio = 1 --Handle if more than one related comment was updated

END

GO

UPDATE TMP_TriggerTable SET Comment = 'asd2' WHERE ID = 1

/*

SELECT * FROM TMP_TriggerTable

--Returns--
ID  ID2 Comment
1   1   asd2
2   1   asd2
3   1   asd2
4   2   asd
5   2   asd
6   2   asd
*/