0

我正在使用 SQL Server 2008。我正在寻找一种创造性的方法来保存和更新我们数据库中的日期列表。

我将从应用程序中收集日期列表,我将需要检查每个值是否已经存在,如果不添加,然后删除列表中已存储在数据库中的任何日期。

我能想到的最简单的事情是删除与此特定请求关联的所有日期,然后遍历列表中的每个项目并插入数据库。

有没有人有更优雅的想法?

4

2 回答 2

0

您可以使用合并。您还可以将日期加载到临时表中并进行插入,例如:

with toinsert as (
    select thedate
    from #newdates nd left outer join
         alldates ad
         on nd.thedate = ad.thedate 
    where ad.thedate is null
)
insert into alldates(thedate)
    select thedate
    from toinsert

toinsert 别名使用左外连接来执行“不在”。我经常发现这样效果更好。无论您如何设置查询(像这样或通过合并),您都应该在日期上放入索引。它应该让事情进展得更快。

于 2012-06-25T20:37:51.297 回答
0

I would use a combination of table valued parameters and the NOT EXISTS function. So pass your dates from your application to a stored procedure as a paramater, the stored procedure will then return a list of all the dates inserted back to your application.#

The first step is to create the type so you can pass a list of dates to your procedure:

CREATE TYPE dbo.DateListType AS TABLE (Date DATETIME)

Next create your procedure. I have assumed you date table is called dbo.Dates, you'll obviously need to substitute your table in for this.

CREATE PROCEDURE dbo.InsertDates (@Dates dbo.DateListType READONLY)
AS
BEGIN
    DECLARE @Inserted TABLE (Date DATETIME)

    INSERT INTO dbo.Dates
    OUTPUT inserted.Date INTO @Inserted
    SELECT  Date
    FROM    @Dates d
    WHERE   NOT EXISTS
            (   SELECT  1
                FROM    dbo.Dates
                WHERE   Dates.Date = d.Date
            )

    SELECT  Date
    FROM    @Inserted
END

Not sure what your application is coded in so unfortunately can't suggest any code to call the procedure

于 2012-06-25T22:07:35.093 回答