gpt4 book ai didi

sql - 在 SQL Server 存储过程中使用变量

转载 作者:行者123 更新时间:2023-12-05 00:11:34 25 4
gpt4 key购买 nike

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

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

Msg 102, Level 15, State 1, Procedure Stuck_Docs_WF_Rpt, Line 12
Incorrect syntax near '.'.

这是我的代码:

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

最佳答案

您已经开始使用 Dynamic Sql。我使用了与您相同的过程并使其动态化。

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

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)

关于sql - 在 SQL Server 存储过程中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12624421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com