我可能会建议这些改变......但我不知道你到底在做什么。或者你的数据。
我强烈建议增加一个修改日期您PersonLog表....
alter table PersonLog add Modified_DT datetime default getdate()
此代码的工作对我来说...
CREATE PROCEDURE UpdateInsertPerson (
@PersonId int,
@PersonName nvarchar(40) = null,
@Address nvarchar(60) = null,
@Mobile nvarchar(15) = null
)
AS
BEGIN
INSERT INTO PersonLog (FK_PersonId, PersonName, Address, Mobile)
SELECT Person.PersonID,
Person.PersonName,
Person.Address,
Person.Mobile
FROM Person
WHERE [email protected];
UPDATE Person
SET PersonName = case when @PersonName is not null then @PersonName else PersonName end,
Address = case when @Address is not null then @Address else Address end,
Mobile = case when @Mobile is not null then @Mobile else Mobile end
WHERE PersonId = @PersonID;
END
insert into Person values (1,'kim','123 main st','555-555-5555');
exec UpdateInsertPerson 1,'kim';
exec UpdateInsertPerson 1,'ryan';
exec UpdateInsertPerson 1,'taco';
select * from personlog
select * from Person
这样不会插入一个全新的人。这种方式将...为了这个工作,你的Person.PersonID必须像这样设置:PersonID int IDENTITY(1,1) primary key
。
ALTER PROCEDURE UpdateInsertPerson (
@PersonId int = null,
@PersonName nvarchar(40) = null,
@Address nvarchar(60) = null,
@Mobile nvarchar(15) = null
)
AS
BEGIN
INSERT INTO PersonLog (FK_PersonId, PersonName, Address, Mobile)
SELECT Person.PersonID,
Person.PersonName,
Person.Address,
Person.Mobile
FROM Person
WHERE [email protected];
UPDATE Person
SET PersonName = case when @PersonName is not null then @PersonName else PersonName end,
Address = case when @Address is not null then @Address else Address end,
Mobile = case when @Mobile is not null then @Mobile else Mobile end
WHERE PersonId = @PersonID;
-- this inserts into Person if they didn't already exist
IF @@ROWCOUNT = 0
BEGIN
INSERT Person (PersonName, Address, Mobile) VALUES (@PersonName, @Address, @Mobile);
END
END
您需要在'insert into ... select ...'中添加一个'where ...',其中'person.personid = @ PersonID'可能......究竟是什么错误? (我还会在该表中添加日期时间,以便知道更改何时发生,只是因为) – 2014-10-05 23:27:08
不工作是什么意思?查询是否会抛出错误,产生错误的结果或什么都不做?我们无法访问您的表格。所以,我们无法找出发生的事情。我想你应该在发布这样的问题之前考虑这一点。 – 2014-10-05 23:28:39