简体   繁体   中英

t-sql stored procedure pass FIELD name as a parameter

Stored procedure works fine with SELECT Value1 from Table1... , but I want to change column name on the fly... like Value1 , Value2 so I want to pass ( @Field ) as a parameter.

What am I doing wrong guys? Thanks in advance.

Table1 :

ID   | Location   | Value1   | Value2
---------------------------------------
 1       L01         123.00     234.00
 2       L02         234.00     456.00
 3       L03         456.00     234.00

Columns:

  • Location - nvarchar(50)
  • Value1 - decimal(18, 2)
  • Value2 - decimal(18,2)

Code:

ALTER PROCEDURE [dbo].[sp_GetFieldValue]
    @Loc nvarchar(50),
    @Field nvarchar(50),   <--------- Error converting data type nvarchar to numeric.
    @Field_Out decimal(18,2) OUTPUT
AS
BEGIN  
    SET NOCOUNT ON;
    SET @Field_Out = (SELECT @Field from Table1 WHERE Location=@Loc)
END

I've tried with no result:

(SELECT CONVERT(decimal(18,2),@Field) from ...
(SELECT ' + @Field +' from ...

I'm executing from Object Explorer, on the left right mouse click "Execute Stored Procedure"

You need to use dynamic SQL to do this. For example:

DECLARE @Query AS VARCHAR(MAX)
SET @Query = 'SELECT [' + @Field + '] from Table1 WHERE Location= ''' + @Loc + ''''
EXECUTE(@Query)

An idea would be sent another param, @Field_No, indicating the field to be returned.

ALTER PROCEDURE [dbo].[sp_GetFieldValue]
@Loc nvarchar(50),
@Field_No TINYINT,
@Field_Out decimal(18,2) OUTPUT
AS
BEGIN  
    SET NOCOUNT ON;

    SELECT @Field_Out = CASE Field_No
                        WHEN 1 THEN Value1
                        WHEN 2 THEN Value2
                    END    
    FROM Table1
    WHERE Location=@Loc
END

Later edit 1:

Solution provided by @roryap is also viable, but to compare:

  • 1/ if your query gets bigger, with even more parameters => it will be difficult to manage it.
  • 2/ Any syntax error will be discovered at design time (aka run time with EXEC ).
  • 3/ I would avoid dynamically SQLs (aka EXEC), as query plans are differently cached. Just imagine the the server could not guess upfront what's behind that string. It would have been better with sp_executesql , but you can't use in this case. It will help if anyone could give more explanations here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM