SQL Dynamic SQL Help: Msg 203, Level 16, State 2, Line 37

Micah Holmes 121 Reputation points
2021-10-27T15:54:05.543+00:00

building a dynamic SQL and getting a error. No idea why keeps erroring:

DECLARE @Query AS NVARCHAR(MAX) = 'SELECT ' + @Rune + ' FROM [White_Box_Gaming].[dbo].[Inventory_Runes] WHERE Email = ''' + @tiedtlaw email + ''''

Also tried:

DECLARE @Query AS NVARCHAR(MAX) = 'SELECT ' + @Rune + ' FROM [White_Box_Gaming].[dbo].[Inventory_Runes] WHERE Email = ''' + @Email + ''  

Msg 203, Level 16, State 2, Line 37
The name 'SELECT Rune_ri FROM [White_Box_Gaming].[dbo].[Inventory_Runes] WHERE Email = 'uokgames@Stuff .com' is not a valid identifier.

Soo annoying.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,653 questions
{count} votes

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 100.8K Reputation points MVP
    2021-10-27T21:45:40.457+00:00

    This is a better solution:

    DECLARE @Result_1 TABLE (ss BIGINT)
    DECLARE @Query AS NVARCHAR(MAX) = 
       'SELECT ' + @Rune + ' FROM [White_Box_Gaming].[dbo].[Inventory_Runes] WHERE Email = @Email'
    INSERT INTO @Result_1 EXEC sp_executesql @Query, N'@Email nvarchar(50)', @Email
    

    You should never inline parameter values into queries. It is better from all aspects to use parameterised statements.

    I don't know what is in this @Rune, but may be possible to deal with it in a similar way.

    0 comments No comments