我有这样的商店程序:
ALTER procedure [dbo].[ParkingSummary1] @startdate varchar(100), @enddate varchar(100) as begin
declare @date1 datetime = CONVERT(datetime, @startdate + ' 00:01:00.000', 120);
declare @date2 datetime = CONVERT(datetime, @enddate + ' 23:23:59.000', 120);
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Vtype)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT LocName, ' + @cols + '
from
( select l.LocName,Vtype from Transaction_tbl t join VType_tbl v on t.vtid = v.vtid
join dbo.Location_tbl l on t.locid=l.Locid where dtime between '''+ @date1+''' and '''+@date2+''' and Status = 5 ) d
pivot
(
count(Vtype)
for Vtype in (' + @cols + ')
) p ' exec sys.sp_executesql @query
end
。我正在通过startand enddate这样:
@startdate = '2013-08-05',@enddate = '2013-08-08'
我收到这样的错误:从字符串转换日期和/或时间时转换失败。 我的存储过程出了什么问题?而不是Date1和date2,如果我通过startdate和enddate然后它将工作。但是如果我给出相同的日期然后没有任何结果的那个时间
答案 0 :(得分:1)
我会使用SET DATEFORMAT YMD
作为存储过程的第一行。
ALTER procedure [dbo].[ParkingSummary1] @startdate varchar(100), @enddate varchar(100)
AS
BEGIN
SET DATEFORMAT DMY
declare @date1 datetime = CONVERT(datetime, @startdate + ' 00:01:00.000', 120);
declare @date2 datetime = CONVERT(datetime, @enddate + ' 23:23:59.000', 120);
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Vtype)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT LocName, ' + @cols + '
from
( select l.LocName,Vtype from Transaction_tbl t join VType_tbl v on t.vtid = v.vtid
join dbo.Location_tbl l on t.locid=l.Locid where dtime between '''+ @date1+''' and '''+@date2+''' and Status = 5 ) d
pivot
(
count(Vtype)
for Vtype in (' + @cols + ')
) p ' exec sys.sp_executesql @query
END
答案 1 :(得分:0)
我不得不替换
declare @date1 datetime = CONVERT(datetime, @startdate + ' 00:01:00.000', 120);
declare @date2 datetime = CONVERT(datetime, @enddate + ' 23:23:59.000', 120);
通过
declare @date1 nvarchar(100) = convert(varchar, @startdate+' 00:00:00.000', 120)
declare @date2 nvarchar(100) = convert(varchar, @enddate+' 23:59:59.000', 120)