SQL Stored-Proc使用服务器名称的参数?

时间:2009-01-28 00:26:50

标签: sql sql-server

我有一个存储过程,它从SQL Server获取所有非系统数据库名称:

select name from MySQLServer.master.sys.databases
where name not like ('master')
and name not like ('tempdb')
and name not like ('msdb')
and name not like ('model')
and name not like ('Admin')

我想要做的是将服务器名称作为参数传递,因此这个sproc更可重用:

@servername = 'some passed servername'

select name from @servername.master.sys.databases
where name not like ('master')
and name not like ('tempdb')
and name not like ('msdb')
and name not like ('model')
and name not like ('Admin')

可以这样做吗?我该怎么做?

我可以创建一个变量:

DECLARE @serverPointer nvarchar(MAX)
SET @serverPointer = @servername + '.master.sys.databases'

select name from @serverPointer

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:2)

如果您将服务器链接到要查询的所有SQL Server,则此功能将起作用。对于要使用的查询,系统数据库占用前4个database_id值。因此,您可以运行以下命令来获取用户数据库:

SELECT '[' + name + ']' 
FROM sys.databases
WHERE database_id > 4

把它放在一起,你基本上会为你的proc做以下事情:

CREATE PROC GetUserDBs
  @Server sysname
AS
BEGIN
  DECLARE @SQL nvarchar(2000);
  SET @SQL = 'SELECT ''['' + name + '']'' FROM [' + @Server + '].master.sys.databases WHERE database_id > 4';
  EXECUTE sp_executesql @SQL;
END
GO

答案 1 :(得分:1)

declare @servername nvarchar(max)
DECLARE @serverPointer nvarchar(MAX)
declare @qry nvarchar(max) 
@serverPointer = @servername + '.master.sys.databases' 
set @qry = 'select name from '+@serverPointer
exec sp_executesql @qry

答案 2 :(得分:0)

为此,您需要在存储过程中创建一个动态查询并使用exec命令执行它,这里有几个例子:

http://www.sqlteam.com/article/introduction-to-dynamic-sql-part-1

http://www.sqlteam.com/article/introduction-to-dynamic-sql-part-2

答案 3 :(得分:0)

Declare @query as varchar(1000)

set @query = ''
+ CHAR(10) + ' select name from '+ CAST(@servername AS VARCHAR(15))+'.master.sys.databases'
+ CHAR(10) +  'where name not in (''master'',''tempdb'',''msdb'',''model'',''Admin'')'

--print (@query)
exec (@query)