Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a User defined table type with a temporary stored procedure

Tags:

sql

sql-server

I am having trouble using a user defined table type as a parameter type to a temporary stored procedure.

I am doing all of this within the database that houses our temp tables, temp stored procedures,... temp anything.

The code looks like this:

CREATE TYPE test_type AS TABLE (user int, user_value int) 
GO

CREATE PROCEDURE #test_pro 
    @input test_type READONLY
AS
    SELECT TOP 10 * 
    FROM @input 
GO

I get the error:

Parameter or variable @input has an invalid data type.

Is there a way for me to use the data type test_type as a type in my temporary stored procedure? I unfortunately only have access to temporary stored procedures and not the permanent version.

Side question: would using a function work any better?

like image 806
H_1317 Avatar asked Sep 05 '25 03:09

H_1317


1 Answers

You need to create the UDT in tempdb.

The following works fine

USE tempdb

GO

CREATE TYPE test_type AS TABLE ([user] int, user_value int)

GO

--Switch database
USE msdb

GO

CREATE PROCEDURE #test_pro @input TEST_TYPE READONLY
AS
    SELECT TOP 10 *
    FROM   @input

GO

EXEC #test_pro

GO

USE tempdb

DROP TYPE test_type

DROP PROC #test_pro 

If you don't have CREATE TYPE permissions in tempdb you can potentially use a #temp table instead.

e.g. the following works

CREATE PROCEDURE #test_pro 
AS
    SELECT TOP 10 * 
    FROM #input 
GO

GO

CREATE TABLE #input([user] int, user_value int) 

GO

EXEC #test_pro
like image 170
Martin Smith Avatar answered Sep 08 '25 00:09

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!