存储过程传递日期参数获取错误

时间:2013-06-22 07:40:08

标签: sql-server

alter procedure [dbo].[ParkingDeatailsReport] 
  @locid INTEGER, @startdate nvarchar(100),@enddate nvarchar(100)
 as
begin
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 Date, ' + @cols + ' 
  from  ( select v.Vtype, convert(date, dtime) as Date 
  from Transaction_tbl t inner join VType_tbl v  
   on t.vtid = v.vtid 
  where dtime between @startdate and @enddate
  and locid =  ' + CAST(@locid as varchar(max)) 
 + '  ) d pivot ( count(Vtype)     for Vtype in (' + @cols + ')  ) p '
execute(@query)
end

我试图像这样执行:

exec ParkingDeatailsReport 5,'2013-01-01 00:00:00','2013-06-18 23:59:59'

但是,我收到一个错误:必须声明标量变量“@startdate”。

1 个答案:

答案 0 :(得分:1)

问题是你在proc中构建SQL,但你没有使用@startdate和@enddate中的值,而是传递字符串

构建字符串时需要获取这些变量的值 - 例如:

ALTER PROCEDURE [dbo].[ParkingDeatailsReport] 
  @locid INTEGER, 
  @startdate nvarchar(100),
  @enddate nvarchar(100)
as
BEGIN
  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 Date, ' + @cols + ' 
                FROM  ( 
                  SELECT 
                    v.Vtype, 
                    convert(date, dtime) as Date 
                  FROM Transaction_tbl t 
                  INNER JOIN VType_tbl v  
                  ON t.vtid = v.vtid 
                  WHERE 
                    dtime between ''' + @startdate + ''' and ''' + @enddate + ''' 
                  AND locid =  ' + CAST(@locid as varchar(max)) + '  
                ) d 
                PIVOT ( count(Vtype)     
                FOR Vtype in (' + @cols + ')  ) p '

  EXECUTE(@query)
END