如何使用一个数据库表到另一个数据库的存储过程,动态传递数据库名称
现在我通常使用一个数据库表到另一个数据库存储过程(数据库名称..表名称
),但我动态传递数据库名称如何编写存储过程请给我任何
我正在写的 建议像这样
Select QT.Name,SC.Name as Status,QT.QuoteNumber,QT.PolicyNumber,LC.Name as LineCode,QT.DBAName as DBAName
from QMSV3Dev..Quote QT, QMSV3Dev..StatusCode SC, QMSV3Dev..LineCode LC
where QT.StatusCode = SC.StatusCode And QT.LineCode = LC.LineCode and
QT.DBAName like 'a%' order by QT.Name,QuoteNumber desc
在上面的存储过程QMSV3Dev..Quote
中,QMSV3Dev
是数据库名称,Quote
是表名称,这个sp在另一个数据库中执行,例如test
now
相同的查询动态传递数据库名称
CREATE Procedure [dbo].[usp_GetSearch123]
(
@SearchValue varchar(100),
@SearchBy varchar(250),
@DbName varchar(50)
)
AS
Begin
Select QT.Name,SC.Name as Status,QT.QuoteNumber,QT.PolicyNumber,LC.Name as LineCode,QT.DBAName as DBAName
from @DbName+'..Quote ' QT,@DbName+'.. StatusCode' SC, @DbName+'..Linecodes' LC
where QT.StatusCode = SC.StatusCode And QT.LineCode = LC.LineCode and
(QT.Name like @SearchValue+'%' or QT.DBAName like @SearchValue+'%')
order by QT.Name,QuoteNumber desc
end
Now I am using one database table to another database stored procedure normally (database name..table name
) but I have dynamically pass the database name how to write the stored procedure pls give me any suggestion
I am writing like this
Select QT.Name,SC.Name as Status,QT.QuoteNumber,QT.PolicyNumber,LC.Name as LineCode,QT.DBAName as DBAName
from QMSV3Dev..Quote QT, QMSV3Dev..StatusCode SC, QMSV3Dev..LineCode LC
where QT.StatusCode = SC.StatusCode And QT.LineCode = LC.LineCode and
QT.DBAName like 'a%' order by QT.Name,QuoteNumber desc
In above stored procedure QMSV3Dev..Quote
, QMSV3Dev
is the database name and Quote
is table name, this sp executed in another database like test
now
Same query pass the database name dynamically
CREATE Procedure [dbo].[usp_GetSearch123]
(
@SearchValue varchar(100),
@SearchBy varchar(250),
@DbName varchar(50)
)
AS
Begin
Select QT.Name,SC.Name as Status,QT.QuoteNumber,QT.PolicyNumber,LC.Name as LineCode,QT.DBAName as DBAName
from @DbName+'..Quote ' QT,@DbName+'.. StatusCode' SC, @DbName+'..Linecodes' LC
where QT.StatusCode = SC.StatusCode And QT.LineCode = LC.LineCode and
(QT.Name like @SearchValue+'%' or QT.DBAName like @SearchValue+'%')
order by QT.Name,QuoteNumber desc
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案比你想象的更简单。为此,您必须使用动态 SQL。
它会是这样的:
您创建一个
varchar
变量@cmd
并将 select 放在它上面,然后通过exec(@cmd)
。The answer is simpler that you think. For that, you have to use Dynamic SQL.
It would be something like this:
You create a
varchar
variable@cmd
and put the select on it and afterwards execute it byexec(@cmd)
.