0

我有这样的存储过程:

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

.while 我像这样传递 start 和 enddate:

@startdate = '2013-08-05',@enddate = '2013-08-08'

我收到这样的错误:从字符串转换日期和/或时间时转换失败。我的存储过程有什么问题?如果我通过 startdate 和 enddate 而不是 Date1 和 date2 那么它将起作用。但是如果我给出相同的日期,那么那个时候不会有任何结果

4

2 回答 2

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
于 2013-08-26T08:27:49.260 回答
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)
于 2013-08-26T10:32:41.893 回答