Passing Table Valued parameter to stored procedure across different databases

一曲冷凌霜 提交于 2019-11-29 09:42:51

In response to this comment (if I'm correct and that using TVPs between databases isn't possible):

What choice do I have in this situation? Using XML type?

The purist approach would be to say that if both databases are working with the same data, they ought to be merged into a single database. The pragmatist realizes that this isn't always possible - but since you can obviously change both the caller and callee, maybe just use a temp table that both stored procs know about.


I don't believe it's possible - you can't reference a table type from another database, and even with identical type definitions in both DBs, a value of one type isn't assignable to the other.


You don't pass the temp table between databases. A temp table is always stored in tempdb, and is accessible to your connection, so long as the connection is open and the temp table isn't dropped.

So, you create the temp table in the caller:

CREATE TABLE #Values (ID int not null,ColA varchar(10) not null)
INSERT INTO #Values (ID,ColA)
/* Whatever you do to populate the table */
EXEC OtherDB..OtherProc

And then in the callee:

CREATE PROCEDURE OtherProc
/* No parameter passed */
AS
    SELECT * from #Values

Table UDTs are only valid for stored procs within the same database.

So yes you would have to create the type on each server and reference it in the stored procs - e.g. just run the first part of this example in both DBs http://msdn.microsoft.com/en-us/library/bb510489.aspx.

If you don't need the efficency you can always use other methods - i.e. pass an xml document parameter or have the s.p. expect a temp table with the input data.

Edit: added example

create database Test1
create database Test2
go
use Test1
create type PersonalMessage as TABLE
(Message varchar(50))
go
create proc InsertPersonalMessage @Message PersonalMessage READONLY AS
  select * from @Message
go
use Test2
create type PersonalMessage as TABLE
(Message varchar(50))
go
create proc InsertPersonalMessage @Message PersonalMessage READONLY AS
  select * from @Message
go
use Test1
declare @mymsg PersonalMessage
insert @mymsg select 'oh noes'
exec InsertPersonalMessage @mymsg 
go
use Test2
declare @mymsg2 PersonalMessage
insert @mymsg2 select 'oh noes'
exec InsertPersonalMessage @mymsg2 

Disadvantage is that there are two copies of the data. But you would be able to run the batch against each database simultaneously. Whether this is any better than using a table table is really down to what processing/data sizes you have - btw to use a temp table from an s.p. you just access it from the s.p. code (and it fails if it doesn't exist).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!