CodexBloom - Programming Q&A Platform

SQL Server: Unexpected 'Invalid column name' scenarios when using dynamic SQL with EXEC sp_executesql

πŸ‘€ Views: 14 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
sql-server dynamic-sql sp_executesql SQL

I'm relatively new to this, so bear with me. After trying multiple solutions online, I still can't figure this out. I'm working with an scenario with executing dynamic SQL in SQL Server 2019 where I'm getting an 'Invalid column name' behavior even though the column exists in the table. The SQL statement is constructed dynamically based on user input, and I'm using `EXEC sp_executesql` to run it. Here’s a simplified example of what I'm doing: ```sql DECLARE @sql NVARCHAR(MAX); DECLARE @columnName NVARCHAR(128) = 'MyColumn'; SET @sql = N'SELECT * FROM MyTable WHERE ' + QUOTENAME(@columnName) + ' = @value'; EXEC sp_executesql @sql, N'@value INT', @value = 10; ``` The `MyTable` has a column named `MyColumn`, so I'm not sure why I’m working with this behavior. I’ve also tried running the dynamic SQL without parameters and it executes successfully: ```sql SET @sql = N'SELECT * FROM MyTable WHERE ' + QUOTENAME(@columnName) + ' = 10'; EXEC sp_executesql @sql; ``` This works as expected, but when I try to use parameters, it fails with 'Invalid column name'. I suspect it might be related to how I'm constructing the SQL string or passing parameters. I've checked for typos and ensured that the column name is correctly spelled and exists in the table schema. Is there something I'm missing about how `sp_executesql` handles column names or parameters? Any insights would be greatly appreciated! What am I doing wrong? I'm working on a CLI tool that needs to handle this. Any ideas what could be causing this?