简体   繁体   English

如何在T-SQL存储过程中访问另一个数据库中的表

[英]How to access table in another database in T-SQL stored procedure

I can access tables in another database OK using the fully qualified name like 我可以使用完全限定名称访问另一个数据库中的表,例如

select * from [DEV-test].dbo.ArchiveCutoff

Now I want to do the same table in a stored procedure. 现在,我想在存储过程中执行相同的表。

My code is 我的代码是

create procedure test  
    @src varchar (128) 
as
begin
  set @src = '[DEV-test]'
  select * from  @src.dbo.ArchiveCutoff
end

But I get an error: 但是我得到一个错误:

Msg 102, Level 15, State 1, Line 12 Msg 102,第15级,状态1,第12行
Incorrect syntax near '.'. '。'附近的语法不正确。

What is the correct way to do this. 正确的方法是什么?

You seem to be looking for Dynamic SQL, using one of the textbook examples . 您似乎正在使用教科书示例之一来寻找Dynamic SQL。 This is generally a bad idea, though there are workarounds. 尽管有解决方法,但这通常不是一个好主意。 If you read the linked article, some suggestions are offered. 如果您阅读链接的文章,则会提供一些建议。

If you absolutely have to use it, though, you are looking for 如果您绝对必须使用它,那么您正在寻找

create procedure test  @src varchar (128) as
begin

 set @src = QUOTENAME(@src) -- leave this 
 set @src = '[DEV-test]'

 declare @sql varchar(200)
 set @Sql = 'select * from ' + @src + '.dbo.ArchiveCutoff'

 EXEC (@SQL)


end

or 要么

create procedure test  @src varchar (128) as
begin

 set @src = QUOTENAME(@src) -- leave this 
 set @src = '[DEV-test]'


 EXEC ('select * from ' + @src + '.dbo.ArchiveCutoff')


end

Use the inline query 使用内联查询

create procedure test 
( @src varchar (128) )as
begin
 set @src = '[DEV-test]'
 declare @x varchar(100)
 @x = 'select * from' +  @src +'.dbo.ArchiveCutoff'
 exec(@x)
end

I am posting a modification to the previous two answers. 我正在发布对前两个答案的修改。 I realize in your code you pass in a parameter and then set it to a hardcoded value. 我意识到在您的代码中您传入了一个参数,然后将其设置为硬编码值。 I assume that is for testing purposes. 我认为这是出于测试目的。 The problem is that both of the posted solutions are vulnerable to sql injection once you remove that line. 问题在于,一旦删除该行,两个发布的解决方案都容易受到sql注入的攻击。 A minor change to both of the excellent previous answers might be like this to prevent sql injection. 对两个出色的先前答案进行较小的更改可能是为了防止sql注入。

create procedure test 
( 
    @src varchar (128) 
)as
    --Presumably this line will be removed after testing. 
    --And because we are using QUOTENAME you want the actual name here with no brackets.
    set @src = 'DEV-test' 

    set @src = QUOTENAME(@src) --This is to help prevent sql injection
    declare @x nvarchar(100)
    set @x = N'select * from ' +  @src +'.dbo.ArchiveCutoff'
    --uncomment the exec line when comfortable your code is correct
    --exec sp_executesql @x

    select @x
GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM