变量中select语句的SQL存储值 [英] SQL store value of select statement in variable
本文介绍了变量中select语句的SQL存储值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下代码打印出前12个月,但它会在tabe中的一列中填充。如何在变量中填充这12个月?我应该尝试使用while循环吗?
have the below code which prints out the previous 12 months however it populates in one column in a tabe. How do I get these 12 months to be populated within a variable? Should I try using a while loop?
declare @date date = '03 December 2015'
;WITH T AS(
SELECT
DATEADD(month, -1, @date) AS Start,
12 Cnt
UNION ALL
SELECT
DATEADD(month, -1, Start),
Cnt-1
FROM T
WHERE Cnt-1>=0
)
SELECT case when LEN(MONTH(Start)) = 1 then substring( cast(YEAR(start) as varchar(6)) + right('0',1)+ cast(MONTH(Start) as varchar(6)),1,10)
else substring( cast(YEAR(start) as varchar(6)) + cast(MONTH(Start) as varchar(6)),1,10) end [YearMonth]
FROM t
推荐答案
我已在解决方案中进行了更改。而不是提供整数输入我建议在日期提供输入,如2014年2月1日'而不是201402.
I have made changes in the solution. Instead of providing input as integer I suggest to provide input in date like 01-Feb-2014' instead of 201402.
DECLARE @TBL_MONTH DATETIME, @NAME AS VARCHAR(20), @CurrentMonth INT, @TMP_MONTH DATETIME,
@Table_Name VARCHAR(20)
SELECT @TBL_MONTH = '01-FEB-2014', @CurrentMonth = 12
WHILE @CurrentMonth > 0
BEGIN
SET @CurrentMonth = @CurrentMonth - 1
SET @TMP_MONTH = DATEADD(month, @CurrentMonth*-1, @TBL_MONTH)
SELECT @NAME = CONVERT(VARCHAR(6), @TMP_MONTH, 112)
PRINT @NAME
SELECT @Table_Name = 'xx_'+@NAME
PRINT @Table_Name
END
它给你你想要什么。
It gives you what you wanted.
DECLARE @FirstTableMonth varchar(6) = 201402
DECLARE @inDate Date , @toDate Date
SET @inDate = Convert(DATE, @FirstTableMonth + '01')
SET @toDate = DATEADD(month, -10,@inDate)
;with months (idate)
AS
(
SELECT @inDate
UNION ALL
SELECT DATEADD(month,-1,isnull(idate,@inDate))
from months
where idate >= @toDate
)
select CONVERT(CHAR(6), idate, 112) from months
option (maxrecursion 0)
201402
201401
201312
201311
201310
201309
201308
201307
201306
201305
201304
201303
201402
201401
201312
201311
201310
201309
201308
201307
201306
201305
201304
201303
declare @date date = '03 December 2015'
declare @list varchar(500)
SET @list = (SELECT LEFT(CONVERT(VARCHAR,DATEADD(MM, -1*number, @date),112),6) + CHAR(10)
FROM master.dbo.spt_values
WHERE TYPE = 'P' and number between 1 and 12
for xml path(''))
select @list
这篇关于变量中select语句的SQL存储值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文