我在master
数据库中创建了一个存储过程,因为我希望能够在各种数据库上运行。
我为database
创建了一个变量,所以当我执行存储过程时,它会在我想要的那个上运行。我一直收到这种语法错误:
Msg 102,Level 15,State 1,Procedure Stuck_Docs_WF_Rpt,Line 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
答案 0 :(得分:1)
您已经开始使用Dynamic Sql了。我使用了相同的proc并使其动态化。
另外,如果你使用的数据库名称少于25个字符,我用varchar而不是char替换@Database变量。
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)