基本上我要将这些多选值传递给我的存储过程:
'April 2016, May 2016, June 2016, July 2016'
值可能超过4。
我如何使用存储过程返回列表的第一个和最后一个日期?
预期输出如:
2016-04-01
2016-07-31
答案 0 :(得分:1)
尝试这个 -
1它更改为XML,
从XML文档中读取2个
3将文本更改为日期(希望!可能是系统依赖)
4选择最小值和最大值,转换为最大值的最后一天
按日期顺序显示5个
declare @list nvarchar(max) = 'April 2016, May 2016, June 2016, July 2016';
DECLARE @XML nvarchar(max) = '<nub><rec><dat>' + REPLACE(@list, ',', '</dat></rec><rec><dat>') + '</dat></rec></nub>';
select @xml;
DECLARE @iX INT
EXEC sp_xml_preparedocument @ix output, @xml;
WITH CTE AS (SELECT CAST('01 ' + dat AS DATETIME) dat_sort ,dat dat FROM OPENXML(@ix, '//rec', 2)
WITH (dat varchar(50))),
MIND AS (select MIN(dat_sort) M from cte UNION SELECT dateadd(day, -1,dateadd(month, 1, MAX(dat_sort))) M from cte)
SELECT M from MIND ORDER BY M
--this is needed to avoid memory leak
EXEC sp_xml_removedocument @iX
答案 1 :(得分:0)
在临时表中插入所有行,并在过程中查找最小和最大日期。如果您以逗号分隔列表传递,请确保它应转换为行。
SELECT CONVERT(DATETIME, 'Apr 2016') date_v
INTO #t11
UNION ALL
SELECT CONVERT(DATETIME, 'may 2016')
UNION ALL
SELECT CONVERT(DATETIME, 'june 2016')
UNION ALL
SELECT CONVERT(DATETIME, 'july 2016')
SELECT Min(date_v) min_date,
Max(date_v) max_date
FROM #t11
更新: 我相信你是以逗号分隔列表传递的 对于以下方法
DECLARE @TOKENS VARCHAR(MAX)='AUG 2016,APR 2016'
DECLARE @list XML
SELECT @list = Cast('<a>' + Replace(@tokens, ',', '</a><a>')
+ '</a>' AS XML)
SELECT Ltrim(t.value('.', 'varchar(200)'))AS data
INTO #tr
FROM @list.nodes('/a') AS x(t)
SELECT Min(CONVERT(DATETIME, data)),
Max(CONVERT(DATETIME, data))
FROM #tr
使用EOMONTH
更新帖子以获取最长日期
declare @tokens varchar(max)='aug 2016,apr 2016'
declare @list xml
select @list = cast('<a>' + replace(@tokens, ',', '</a><a>')
+ '</a>' as xml)
select ltrim(t.value('.', 'varchar(200)'))as data
into #tr1
from @list.nodes('/a') as x(t)
select min(convert(datetime, data)),
eomonth((max(convert(datetime, data))))
from #tr1