1

我习惯这样做:

use MyDb
go
create type table_list as table (name sysname)
go
create proc rebuild_indexes
    @ls table_list readonly
as
  [...]

但现在我想在master中创建 proc并在其他数据库中使用它:

use master
go
create type table_list as table (name sysname)
go
create proc sp_rebuild_indexes
    @ls table_list readonly
as
  [...]

...它构建得很好,但我不能使用它!

use MyDb
go
declare @ls table_list

产量:

消息 2715,级别 16,状态 3,第 1 行列、参数或变量 #1:找不到数据类型 table_list。参数或变量“@ls”的数据类型无效。

所以我尝试创建一个同义词,它在创建过程中不会抱怨但没有帮助:

create synonym table_list for master.dbo.table_list

任何人的想法?

4

2 回答 2

2

Table types declared in different databases, even if they share the same name and structure, are not treated as being the same by SQL Server:

create database DB1
go
use DB1
go
create type TT1 as table (ID int not null)
go
create procedure Echo
    @T TT1 readonly
as
    select * from @T
go
create database DB2
go
use DB2
go
create type TT1 as table (ID int not null)
go
declare @T TT1
insert into @T(ID) values (1)
exec DB1..Echo @T

Result:

(1 row(s) affected)
Msg 206, Level 16, State 2, Procedure Echo, Line 0
Operand type clash: TT1 is incompatible with TT1

So far as I'm aware, there is no way to declare a variable in a database using a table type definition from another database. (e.g. anywhere where you see a user defined table type can be used, it can only be named as <table type> or <schema>.<table type>. 3 or 4 part names are not allowed)

(The above is true for 2008 and 2012; obviously, future versions may do something to address this)


As a work-around, you can do it the "poor man's" way - have your master defined stored procedure work against a temp table, rather than a user defined table type:

use Master
go
create procedure sp_Echo
as
    select DB_NAME(),* from #t
go
create database DB1
go
use DB1
go
create table #t (ID int not null)
insert into #t (ID) values (1),(2)
exec sp_Echo

Results:

------------- -----------
DB1           1
DB1           2
于 2012-10-04T06:15:40.030 回答
1

AFAIK,用户定义的类型不能在创建它们的数据库的上下文之外使用。

您可能必须在每个数据库中创建 UDT,但将 sProc 保留在 master 中。

您使用 sp_ 命名约定是否有特定原因?

皮特

于 2012-10-04T05:55:20.917 回答