我可能會建議這些改變......但我不知道你到底在做什麼。或者你的數據。
我強烈建議增加一個修改日期您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