0

我试图弄清楚如何在 where 子句中使用循环。我有这段代码,我只想要过去 7 天的文件名。到目前为止它有效,我只是想让代码更动态/更好:)

select a, b
from data1
where a in 
(
  'File_'+CAST(YEAR(GETDATE()-1)*10000+MONTH(GETDATE()-1)*100+DAY(GETDATE()-1) 
      AS VARCHAR)+'.TXT'
, 'File_'+CAST(YEAR(GETDATE()-2)*10000+MONTH(GETDATE()-2)*100+DAY(GETDATE()-2) 
      AS VARCHAR)+'.TXT'
, 'File_'+CAST(YEAR(GETDATE()-3)*10000+MONTH(GETDATE()-3)*100+DAY(GETDATE()-3) 
      AS VARCHAR)+'.TXT'
, 'File_'+CAST(YEAR(GETDATE()-4)*10000+MONTH(GETDATE()-4)*100+DAY(GETDATE()-4) 
      AS VARCHAR)+'.TXT'
, 'File_'+CAST(YEAR(GETDATE()-5)*10000+MONTH(GETDATE()-5)*100+DAY(GETDATE()-5) 
      AS VARCHAR)+'.TXT'
, 'File_'+CAST(YEAR(GETDATE()-6)*10000+MONTH(GETDATE()-6)*100+DAY(GETDATE()-6) 
      AS VARCHAR)+'.TXT'
, 'File_'+CAST(YEAR(GETDATE()-7)*10000+MONTH(GETDATE()-7)*100+DAY(GETDATE()-7) 
      AS VARCHAR)+'.TXT'
)
order by a

文件名称为 File_YYYYMMDD.txt。

我搜索了其他地方并阅读了一些关于循环的内容,但我能想到的只是这样的事情,但它不起作用:

DECLARE @i int = 0
WHILE @i < 7 BEGIN
    SET @i = @i + 1
END

select a, b
from data1
where a in 
(
  'File_'+CAST(YEAR(GETDATE()-@i)*10000+MONTH(GETDATE()-@i)*100+DAY(GETDATE()-@i) 
     AS VARCHAR)+'.TXT'
)
order by a
4

1 回答 1

1

不要再考虑循环了。SQL Server 不是为循环而设计的,它是为使用集合而设计的。看看这个的输出:

;WITH x AS 
(
  SELECT TOP (7) f = 'File_' 
    + CONVERT(CHAR(8), DATEADD(DAY, -ROW_NUMBER() OVER 
   (ORDER BY [object_id]), CAST(GETDATE() AS DATE)), 112) + '.txt'
  FROM sys.all_objects ORDER BY [object_id]
)
SELECT f FROM x;

结果:

f
-----------------
File_20130814.txt
File_20130813.txt
File_20130812.txt
File_20130811.txt
File_20130810.txt
File_20130809.txt
File_20130808.txt

现在,你怎么能使用这个集合?

;WITH x AS 
(
  SELECT TOP (7) f = 'File_' 
    + CONVERT(CHAR(8), DATEADD(DAY, -ROW_NUMBER() OVER 
   (ORDER BY [object_id]), CAST(GETDATE() AS DATE)), 112) + '.txt'
  FROM sys.all_objects ORDER BY [object_id]
)
SELECT d.a, d.b FROM dbo.data1 AS d
WHERE EXISTS 
(
  SELECT 1 FROM x
  WHERE f = d.a
)
ORDER BY d.a;
于 2013-08-15T14:22:31.003 回答