SQL Server中的ForEach循环

时间:2014-01-03 21:15:07

标签: sql foreach sql-server-2012 iteration

我有一个值列表,即

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
....

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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(但请养成在其中放置列列表的习惯)。

答案 2 :(得分:-1)

我认为您可以使用光标,但是您需要将此('1xxx','12xx','21xx','98xx','00xx')

就像这样

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

有关光标的更多信息:

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