SQL Server 中的 ForEach 循环

问题描述 投票:0回答:4

我有一个值列表,即

in ('1xxx','12xx','21xx','98xx','00xx')

我想用于插入脚本。如何使用循环中的每个值在 SQL Server 中编写 for 循环?我想是这样的。

For value in ('1xxx','12xx','21xx','98xx','00xx')
  select value
endloop;

我正在尝试简化这个

    INSERT INTO [dbo].[TimeCard]
    VALUES
            ('test'+Right(NewId(),12),'6121126800','5102289289',CONVERT(DATE,'01-01-2013'),CONVERT(DATE,'01-01-2013'),20,CURRENT_TIMESTAMP,NULL )
    GO

    INSERT INTO [dbo].[TimeCard]
    VALUES
            ('test'+Right(NewId(),12),'6121126800','5102289289',CONVERT(DATE,'01-08-2013'),CONVERT(DATE,'01-08-2013'),20,CURRENT_TIMESTAMP,NULL)
    GO


    INSERT INTO [dbo].[TimeCard]
    VALUES
            ('test'+Right(NewId(),12),'6121126800','5102289289',CONVERT(DATE,'01-15-2013'),CONVERT(DATE,'01-15-2013'),20,CURRENT_TIMESTAMP,NULL )
    GO
....

我必须为几个测试场景插入这些记录。

sql foreach sql-server-2012 iteration
4个回答
1
投票

您不需要昂贵的循环、游标或函数来根据手动提供的这些值构建集合。

DECLARE @start DATE = '20130101', @now DATETIME2(7) = CURRENT_TIMESTAMP;

;WITH months AS 
(
  -- we need 12 months
  SELECT TOP (12) m = number FROM master.dbo.spt_values 
  WHERE type = 'P' ORDER BY number
),
-- we need a week in each month, starting at the 1st
weeks AS (SELECT w FROM (VALUES(0),(1),(2),(3)) AS w(w)),
dates AS 
(
  -- this produces a date for the first 4 weeks of each
  -- month from the start date
  SELECT d = DATEADD(WEEK,w.w,DATEADD(MONTH,m.m,@start)) 
  FROM months AS m CROSS JOIN weeks AS w
),
vals AS 
(
  -- and here are the values you were given
  SELECT v FROM (VALUES('1xxx'),('12xx'),('21xx'),('98xx'),('00xx')) AS v(v)
)
-- INSERT dbo.TimeCard(column list here please)
SELECT 
  'Test' + RIGHT(NEWID(),12),
  '6121126800',
  vals.v,
  dates.d,
  dates.d,
  20,
  @now,
  NULL
FROM dates CROSS JOIN vals
ORDER BY vals.v,dates.d;

这应该返回 240 行(12 个月 * 4 周 * 问题中提供的 5 个值)。当您将输出操作为您期望的结果时,取消注释 INSERT(但请养成在那里放置列列表的习惯)。


1
投票

如果您有逗号分隔的字符串,请使用这 4 个返回表的函数中的一些(http://blogs.msdn.com/b/amitjet/archive/2009/12/11/sql-server-comma-separated-string-到表.aspx)。 将返回的数据插入带有标识列 (1,1) 的临时表中。

之后使用游标或使用之前创建的标识列循环遍历表。 http://technet.microsoft.com/en-us/library/ms178642.aspx


0
投票

对日期使用递归 cte,并为这些示例使用“选择值”语句:

;with dates as (
        select d=convert(date, '2024-01-01')
    union all
        select DATEADD(day, 7, d)
        from dates
        where d < getdate()
    )
select
    'test'+Right(NewId(),12)
    ,v
    ,d
    ,d
    ,20
    ,CURRENT_TIMESTAMP
    ,NULL
from dates d
cross join (SELECT v FROM (VALUES('1xxx'),('12xx'),('21xx'),('98xx'),('00xx')) AS v(v)) v

-1
投票

我认为你可以使用光标,但你需要把这个

('1xxx','12xx','21xx','98xx','00xx')

在这样的事情中

select '1xxx','12xx','21xx','98xx','00xx'

有关光标的更多信息:

http://technet.microsoft.com/pt-br/library/ms180169.aspx

© www.soinside.com 2019 - 2024. All rights reserved.