我试图弄清楚如何在 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