3

我在数据库中创建了一个存储过程,master因为我希望能够在各种数据库上运行。

我为此创建了一个变量,database因此当我执行存储过程时,它将在我想要的那个上运行。我不断收到此语法错误:

消息 102,级别 15,状态 1,过程 Stuck_Docs_WF_Rpt,第 12 行
'.' 附近的语法不正确。

这是我的代码:

ALTER PROCEDURE [dbo].[Stuck_Docs_WF_Rpt] 
   @Database char(25)
AS
BEGIN
   select 
      count(@Database.hsi.itemdata.itemnum) as 'Doc(s) Stuck',
      @Database.hsi.lcstate.statename as 'Queue', 
      @Database.hsi.lifecycle.lifecyclename as 'Lifecycle'
   from 
      @Database.hsi.itemdata
   join 
      @Database.hsi.itemlc on @Database.hsi.itemdata.itemnum = @Database.hsi.itemlc.itemnum
   join 
      @Database.hsi.lcstate on @Database.hsi.itemlc.statenum = 
@Database.hsi.lcstate.statenum
   join 
      @Database.hsi.lifecycle on @Database.hsi.itemlc.lcnum = @Database.hsi.lifecycle.lcnum
   where
       @Database.hsi.itemdata.itemnum = @Database.hsi.itemlc.itemnum 
       and @Database.hsi.lcstate.statenum = @Database.hsi.itemlc.statenum
       and @Database.hsi.lcstate.statename Like '%Route' or @Database.hsi.lcstate.statename like '%Initial'
       and @Database.hsi.itemlc.status = '0'
       and DateDiff([Day], @Database.hsi.itemlc.transdate, getDate()) >=1
    group by @Database.hsi.lifecycle.lifecyclename, @Database.hsi.lcstate.statename
END
4

1 回答 1

1

您已经在走向 Dynamic Sql。我使用了相同的过程并使其动态化。

此外,如果您使用的数据库名称少于 25 个字符,我将 @Database 变量替换为 varchar 而不是 char。

alter PROCEDURE [dbo].[Stuck_Docs_WF_Rpt] 
   @Database varchar(25)
AS
DECLARE @sql varchar(max)

   SELECT @sql = 'select 
      count('+@Database+'.hsi.itemdata.itemnum) as ''Doc(s) Stuck'',
      '+@Database+'.hsi.lcstate.statename as ''Queue'', 
      '+@Database+'.hsi.lifecycle.lifecyclename as ''Lifecycle''
   from 
      '+@Database+'.hsi.itemdata
   join 
      '+@Database+'.hsi.itemlc on '+@Database+'.hsi.itemdata.itemnum = '+@Database+'.hsi.itemlc.itemnum
   join 
      '+@Database+'.hsi.lcstate on '+@Database+'.hsi.itemlc.statenum = 
'+@Database+'.hsi.lcstate.statenum
   join 
      '+@Database+'.hsi.lifecycle on '+@Database+'.hsi.itemlc.lcnum = '+@Database+'.hsi.lifecycle.lcnum
   where
       '+@Database+'.hsi.itemdata.itemnum = '+@Database+'.hsi.itemlc.itemnum 
       and '+@Database+'.hsi.lcstate.statenum = '+@Database+'.hsi.itemlc.statenum
       and '+@Database+'.hsi.lcstate.statename Like ''%Route'' or '+@Database+'.hsi.lcstate.statename like ''%Initial''
       and '+@Database+'.hsi.itemlc.status = ''0''
       and DateDiff([Day], '+@Database+'.hsi.itemlc.transdate, getDate()) >=1
    group by '+@Database+'.hsi.lifecycle.lifecyclename, '+@Database+'.hsi.lcstate.statename'

    print(@sql)
    --exec(@sql)
于 2012-09-27T15:48:02.393 回答