如何使用一个数据库表到另一个数据库存储过程,动态传递数据库名称

时间:2011-12-21 10:08:52

标签: sql-server-2008 stored-procedures asp.net-4.0

现在我正在使用一个数据库表到另一个数据库存储过程(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 

1 个答案:

答案 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)执行。