【问题标题】:Updating one table from another without a one to one relationship在没有一对一关系的情况下从另一个表更新一个表
【发布时间】:2011-03-16 15:43:03
【问题描述】:

我正在尝试填充一个包含未来 35 年每个日期的日期表,其中包含有关每一天的信息。

我的 ERP 系统有一个会计年度表 (GLRULE),它指定了每个特定年份的会计期间,因为许多公司不按日历月工作。

GLRule 表包含每个时期的一条记录,如下所示:

fcbasis  fcname    fcstatus  fdend              fdstart            flisadjust  flisaudit  fnnumber  freval  identity_column
A        FY 2000   C         1/28/2000 0:00:00  1/1/2000 0:00:00   FALSE       FALSE      1         FALSE   37
A        FY 2000   C         2/25/2000 0:00:00  1/29/2000 0:00:00  FALSE       FALSE      2         FALSE   38
A        FY 2000   C         3/31/2000 0:00:00  2/26/2000 0:00:00  FALSE       FALSE      3         FALSE   39
A        FY 2000   C         4/28/2000 0:00:00  4/1/2000 0:00:00   FALSE       FALSE      4         FALSE   40
A        FY 2000   C         5/26/2000 0:00:00  4/29/2000 0:00:00  FALSE       FALSE      5         FALSE   41
A        FY 2000   C         6/30/2000 0:00:00  5/27/2000 0:00:00  FALSE       FALSE      6         FALSE   42

无论如何,我可以使用类似这样的查询一次更新我的日期表一个字段:

UPDATE redfridaydates.dbo.testdates 
   SET [FISCAL_PERIOD]   = 
                (SELECT fnnumber
                  FROM m2mdata01..glrule GLR
                  where DATE >= GLR.FDSTART and DATE <= GLR.FDEND)

有没有更好的方法来一次更新多个字段?我不确定我该怎么做,因为我没有加入。

【问题讨论】:

  • 格式化代码时请不要使用制表符。
  • @Chadwick:谢谢纠正格式!
  • 对不起,我没有使用标签,我从 Excel 电子表格中复制并粘贴了它。

标签: sql sql-server tsql sql-server-2000


【解决方案1】:

也许循环遍历您的日期表是一种解决方案?

declare @myDate SmallDateTime
set @myDate = (Select MIN(DATE) FROM dbo.testdates)

declare @myFiscal int

WHILE @myDate is not null
BEGIN

--determine the fiscal period
--output a zero for missing fiscal periods
SET @myFiscal = isnull(
   (
   SELECT fnnumber 
   FROM m2mdata01..glrule GLR 
   WHERE @myDate >= GLR.FDSTART AND @myDate <= GLR.FDEND
   ),0)

--update the date table
UPDATE redfridaydates.dbo.testdates 
SET fiscal_period = @fiscal
WHERE date = @myDate

--get the next date
--will be null once the loop reaches the end of the table
SET @myDate = (Select MIN(DATE) FROM dbo.testdates WHERE DATE > @myDAte)

END

【讨论】:

    【解决方案2】:

    听起来您要更新的表在每个日期都有一条记录。答案假设是这样。如果您可以确保您的 GL 数据源没有重叠日期:

    UPDATE T
    SET T.[FISCAL_PERIOD] = GLR.fnnumber,
         T.Foo = GLR.Bar,
         T.Bat = GLR.Baz  --etc.
    
    FROM redfridaydates.dbo.testdates  AS T
    INNER JOIN m2mdata01..glrule AS GLR
    ON T.[Date] BETWEEN GLR.FDSTART  AND GLR.FDEND
    

    如果你有兴趣,这里是proof of concept on some test data

    【讨论】:

    • 谢谢,我试试。我无法检查概念证明,因为我的公司屏蔽了该网站。
    【解决方案3】:

    您始终可以在更新查询中设置更多字段:

    UPDATE TableName Set Field1 = (Select fnnumber From ....), 
    Field2 = (some other query or value), etc.
    

    【讨论】:

    • 是的,我很感激。我希望有一种基于集合的方式来处理这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2013-02-15
    • 2013-06-13
    相关资源
    最近更新 更多