具有特定要求的SQL Server中的更新或插入

时间:2016-04-25 15:21:01

标签: sql-server sql-update sql-insert

我需要将记录插入到如下所示的表中:

CREATE TABLE [dbo].[ExamFees]
(
    [ExamSeriesID] [int] NOT NULL,
    [Region] [varchar](50) NOT NULL,
    [Fee] [money] NOT NULL,
    [DatetimeEntered] [datetime] NULL
)

但是,如果记录已经存在,那么我只想将DatetimeEntered设置为GETDATE()。

我认为我需要使用合并,但我不知道如何做到这一点,并且被告知如果我不知道自己在做什么,我会丢失数据。

一些示例数据是:

INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(553, 'Low', 10.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(553, 'Lower mid', 20.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(553, 'Upper mid', 30.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(553, 'High', 40.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(401, 'Low', 5.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(401, 'Lower mid', 10.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(401, 'Upper mid', 15.00, GETDATE())
INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(401, 'High', 20.00, GETDATE())

值得一提的是,这也将从C#程序调用。

SQL是按质量生成的,并添加到StringBuilder中,如下所示:

string Region = "Low";

string ExamFeesTableName = "ExamFees";

sb.AppendLine("INSERT INTO " + ExamFeesTableName + "([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES(" + ExamSeriesID + ", '" + Region + "', " + Fee.ToString("0.00") + ", GETDATE())");

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我建议选择类似于以下方法之一的策略:

方法1

IF EXISTS (SELECT * FROM ExamFees WHERE ExamSeriesID='553' and Region = 'Low')
    UPDATE ExamFees SET DatetimeEntered = GETDATE() WHERE ExamSeriesID='553' and Region = 'Low'
ELSE
    INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES('553', 'Low', 10.00, GETDATE())

方法2

UPDATE ExamFees SET DatetimeEntered = GETDATE() WHERE ExamSeriesID='553' and Region = 'Low'
IF @@ROWCOUNT=0
        INSERT INTO ExamFees([ExamSeriesID], [Region], [Fee], [DatetimeEntered]) VALUES('553', 'Low', 10.00, GETDATE())

这些示例基于您的第一个INSERT语句,需要为每个INSERT语句重复。