现在我正在使用一个数据库表到另一个数据库存储过程(database name..table name
)但是我已动态传递数据库名称如何编写存储过程请给我任何建议
我写的是这样的
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
现在
相同的查询动态传递数据库名称
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
答案 0 :(得分:1)
你认为答案更简单。为此,您必须使用Dynamic SQL。
这将是这样的:
CREATE Procedure [dbo].[usp_GetSearch123]
(
@SearchValue varchar(100),
@SearchBy varchar(250),
@DbName varchar(50)
)
AS
Begin
Declare @cmd varchar(5000)
select @cmd =
'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'
exec(@cmd)
end
您创建了varchar
变量@cmd
并将选择放在其上,然后按exec(@cmd)
执行。