我希望每天只将数据插入数据库一次。问题是我希望sql查询检查这个(因为代码是不可触摸的)
目前,只要有人访问某个网页,就会调用spInsertRate过程。
INSERT INTO dbo.LU_ExchangeRates
(exch_Date,exch_Currency,exch_Rate)
VALUES(@exchDATE,@exchCurrency,@exchRate)
我猜我必须先做一个select语句,如果select语句没有返回一行,那就意味着要运行insert语句。我只是无法弄清楚如何为此编码。
答案 0 :(得分:4)
我在exch_Date列上放了一个唯一约束,然后让spInsertRate运行insert并在失败时捕获异常。
答案 1 :(得分:4)
如果你必须将它作为单个SQL来实现,那么
INSERT INTO dbo.LU_ExchangeRates
(exch_Date,exch_Currency,exch_Rate)
SELECT
@exchDATE,@exchCurrency,@exchRate
WHERE
NOT EXISTS (
SELECT * from dbo.LU_ExchangeRates
WHERE
exch_Date = @exchDATE and exch_Currency = @exchCurrency)
但更常见的是
IF NOT EXISTS (
SELECT * from dbo.LU_ExchangeRates
WHERE
exch_Date = @exchDATE and exch_Currency = @exchCurrency)
INSERT INTO dbo.LU_ExchangeRates
(exch_Date,exch_Currency,exch_Rate)
VALUES
@exchDATE,@exchCurrency,@exchRate
答案 2 :(得分:1)
IF NOT EXISTS (SELECT * FROM dbo.LU_ExchangeRates WHERE exch_Date = @exchDATE)
BEGIN
INSERT INTO dbo.LU_ExchangeRates (exch_Date,exch_Currency,exch_Rate) VALUES(@exchDATE,@exchCurrency,@exchRate)
END
答案 3 :(得分:1)
您可以使用IGNORE_DUP_ROWS选项(或其名称)定义复合唯一索引,然后将以静默方式丢弃任何失败的插入。
这可以在Sybase ASE上完成,也可能不在MS SQL服务器上完成。
答案 4 :(得分:0)
如果在表中找不到今天的日期,我会执行单个查询来执行其插入操作。这样,在选择插入之间就没有竞争了。也许
INSERT INTO dbo.LU_ExchangeRates (...)
SELECT @exchDate, ...
WHERE NOT EXISTS (SELECT *
FROM dbo.LU_ExchangeRates
WHERE exch_date >= @exchDate
AND exch_Currency != @exchCurrency)