无法从另一个表自动获取特定ID

时间:2013-08-04 11:32:53

标签: sql-server

我有一个这样的存储过程:

ALTER procedure [dbo].[ParkingDeatailsReportnew] 
  @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 =  ' + (select l.Locid from Location_tbl l) 
 + '  ) d pivot ( count(Vtype)     for Vtype in (' + @cols + ')  ) p '
execute(@query)
end

执行此查询时出现以下错误:

  

需要参数' @ locid',这是未提供的。我想从我的位置表中获取所有locid

2 个答案:

答案 0 :(得分:0)

您存储过程无法运行,因为您需要获取参数@locid@StartDate@EndDate

EXEC ParkingDeatailsReportnew   
   @logid = [yourvalue], @StartDate = '[somedate]', @enddate = 'someEndDate'

例如:

EXEC ParkingDeatailsReportnew   
   @logid = 1234, @StartDate = '2013/08/04 08:01:00 ', @enddate = '2013/08/04 11:21:00'

解决此问题后,开始解决其他问题

---编辑----

所以你需要从参数中删除它。

ALTER procedure [dbo].[ParkingDeatailsReportnew] 
    @startdate nvarchar(100),@enddate nvarchar(100)

为什么你首先拥有它?
我怀疑它是否有效execute需要VARCHAR,您在使用NVARCHAR时使用了sp_executesql

我还认为你的逻辑中还有其他错误,但你以后会到达那里。

答案 1 :(得分:0)

试试这个 -

ALTER PROCEDURE [dbo].[ParkingDeatailsReportnew] 

    @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 dbo.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 
        join VType_tbl v on t.vtid = v.vtid  
        where dtime between ''' + @startdate + ''' 
            and ''' + @enddate + '''
            and locid =  ' + CAST(@locid AS VARCHAR(10)) +
    '  ) d pivot ( count(Vtype) for Vtype in (' + @cols + ')  ) p '

    EXEC sys.sp_executesql @query
END