Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sp_executesql with params complains of the need to declare a variable

I am attempting to make a stored procedure that uses sp_executesql. I have looked long and hard here, but I cannot see what I am doing incorrectly in my code. I'm new to stored procedures/sql server functions in general so I'm guessing I'm missing something simple. The stored procedure alter happens fine, but when I try run it I'm getting an error.

The error says.

Msg 1087, Level 15, State 2, Line 3
Must declare the table variable "@atableName"

The procedure looks like this.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[sp_TEST]
    @tableName varchar(50),
    @tableIDField varchar(50),
    @tableValueField varchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQLString nvarchar(500);
    SET @SQLString = N'SELECT DISTINCT @aTableIDField FROM @atableName';
    EXEC sp_executesql @SQLString,
            N'@atableName varchar(50),
              @atableIDField varchar(50),
              @atableValueField varchar(50)',
            @atableName = @tableName,
            @atableIDField = @tableIDField,
            @atableValueField = @tableValueField;
END

And I'm trying to call it with something like this.

EXECUTE sp_TEST 'PERSON', 'PERSON.ID', 'PERSON.VALUE'

This example isn't adding anything special, but I have a large number of views that have similar code. If I could get this stored procedure working I could get a lot of repeated code shrunk down considerably.

Thanks for your help.

Edit: I am attempting to do this for easier maintainability purposes. I have multiple views that basically have the same exact sql except the table name is different. Data is brought to the SQL server instance for reporting purposes. When I have a table containing multiple rows per person id, each containing a value, I often need them in a single cell for the users.

like image 773
wilbbe01 Avatar asked Dec 14 '25 13:12

wilbbe01


1 Answers

You can not parameterise a table name, so it will fail with @atableName

You need to concatenate the first bit with atableName, which kind defeats the purpose fo using sp_executesql

like image 68
gbn Avatar answered Dec 17 '25 06:12

gbn



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!