Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass udtt into a stored procedure in SQL Server Management Studio

Tags:

I have a SP prc_Foo_Delete which has the following signature:

ALTER PROCEDURE [prc_Foo_Delete]     @fooIds [int_udtt] READONLY,     @deleteReason int,     @comment nvarchar(512),     @deletedBy nvarchar(128) 

int_udtt is define as:

CREATE TYPE [int_udtt] AS TABLE(     [Id] [int] NOT NULL,     PRIMARY KEY CLUSTERED  (     [Id] ASC )WITH (IGNORE_DUP_KEY = OFF) ) 

I tried to call this SP in Management Studio with following script:

DECLARE @return_value int EXEC    @return_value = [prc_Foo_Delete]         @fooIds = 3,         @deleteReason = 2,         @comment = N'asfdasdf',         @deletedBy = N'asdfa'  SELECT  'Return Value' = @return_value GO 

The error I got is: Operand type clash: int is incompatible with int_udtt. How do I pass in a int or a list of int to call in this tool (I know how to do it in code but not in Management Studio).

like image 404
Icerman Avatar asked Dec 09 '11 00:12

Icerman


People also ask

Can I pass table variable to stored procedure?

You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

How do you pass a list of values into a stored procedure?

There are several ways to do this. While using older versions of SQL Server, I've used to the XML method to pass array or list to stored procedure. In the latest versions of SQL Server, we can use the User Defined Data Type (UDT) with a base type of table to send array or list through a parameter.

Can we use CTE inside stored procedure?

According to the CTE documentation, Common Table Expression is a temporary result set or a table in which we can do CREATE, UPDATE, DELETE but only within that scope. That is, if we create the CTE in a Stored Procedure, we can't use it in another Stored Procedure.


1 Answers

Since you've defined your user defined type as a parameter on the stored procedure, you need to use that user-defined type, too, when calling the stored procedure! You cannot just send in a single INT instead....

Try something like this:

-- define an instance of your user-defined table type DECLARE @IDs [int_udtt]  -- fill some values into that table INSERT INTO @IDs VALUES(3), (5), (17), (42)  -- call your stored proc DECLARE @return_value int EXEC    @return_value = [prc_Foo_Delete]         @fooIds = @IDs,   -- pass in that UDT table type here!         @deleteReason = 2,         @comment = N'asfdasdf',         @deletedBy = N'asdfa'  SELECT  'Return Value' = @return_value GO 
like image 106
marc_s Avatar answered Sep 22 '22 12:09

marc_s