没有循环的动态更新语句

时间:2014-12-11 10:55:35

标签: sql-server sql-server-2008-r2

我必须按照表更新column_name以获取特定日期:

表:testg

create table testg
(
column_date datetime,
column_name varchar(100)
);

记录插入:

insert into testg values('2005-01-01','');
insert into testg values('2005-01-02','');
insert into testg values('2005-01-03','');
insert into testg values('2005-01-04','');
insert into testg values('2005-01-05','');
insert into testg values('2005-01-06','');
insert into testg values('2005-01-07','');
insert into testg values('2005-01-01','');
insert into testg values('2005-01-01','');
insert into testg values('2005-01-08','');
insert into testg values('2005-01-09','');
insert into testg values('2005-01-10','');

注意:现在我想在不使用循环的情况下更新两个日期之间的名称。日期作为参数传递给更新和名称。

Declare @dates varchar(max) = '2005-01-01to2005-01-03,2005-01-04to2005-01-05,2005-01-06to2005-01-08'
Declare @names varchar(max) = 'D1,D2,D3'

必须将名称D1,D2,D3更新为日期

预期结果

    column_date             column_name 
-----------------------------------------       
2005-01-01 00:00:00.000         D1
2005-01-02 00:00:00.000         D1
2005-01-03 00:00:00.000         D1
2005-01-04 00:00:00.000         D2
2005-01-05 00:00:00.000         D2
2005-01-06 00:00:00.000         D3
2005-01-07 00:00:00.000         D3
2005-01-01 00:00:00.000         D1
2005-01-01 00:00:00.000         D1
2005-01-08 00:00:00.000         D3
2005-01-09 00:00:00.000 
2005-01-10 00:00:00.000 

2 个答案:

答案 0 :(得分:2)

您可以使用CASE语句来实现此目的:

UPDATE  testg
SET     column_name = CASE WHEN column_date BETWEEN '2005-01-01' AND '2005-01-03'
                           THEN 'D1'
                           WHEN column_date BETWEEN '2005-01-04' AND '2005-01-05'
                           THEN 'D2'
                           WHEN column_date BETWEEN '2005-01-06' AND '2005-01-08'
                           THEN 'D3'
                           ELSE ''
                      END

Demo SQL Fiddle

答案 1 :(得分:1)

您也可以以表格的形式表示输入并使用它:

UPDATE testg
SET column_name = ISNULL(
  (
    SELECT
      s
    FROM
      (VALUES
        ('2005-01-01', '2005-01-03', 'D1'),
        ('2005-01-01', '2005-01-03', 'D2'),
        ('2005-01-01', '2005-01-03', 'D3')
      ) AS v (d1, d2, s)
    WHERE
      testg.column_date BETWEEN v.d1 AND v.d2
  ),
  ''
);

或者像这样:

UPDATE
  t
SET
  column_name = ISNULL(v.s, '')
FROM
  testg AS t
  LEFT JOIN
    (VALUES
      ('2005-01-01', '2005-01-03', 'D1'),
      ('2005-01-01', '2005-01-03', 'D2'),
      ('2005-01-01', '2005-01-03', 'D3')
    ) AS v (d1, d2, s)
    ON t.column_date BETWEEN v.d1 AND v.d2
;

顺便说一句,请注意,当目标是YYYY-MM-DD时,datetime格式并不明确,这意味着值的解释取决于SET LANGUAGE / SET DATEFORMAT设置。如果在这种情况下您只使用日期,请考虑使用YYYYMMDD格式或切换到date类型(YYYY-MM-DDdate明确无误。)