CodexBloom - Programming Q&A Platform

SQL Server 2019: implementing Dynamic SQL and Parameterized Queries in Stored Procedures

👀 Views: 89 💬 Answers: 1 📅 Created: 2025-06-05
sql-server dynamic-sql stored-procedures sql

I'm working on a project and hit a roadblock. I'm migrating some code and I'm working with an scenario when trying to use dynamic SQL within a stored procedure in SQL Server 2019... I'm attempting to execute a query that includes parameters, but I'm seeing unexpected results, specifically when the parameters are not being substituted correctly. Here's a simplified version of my stored procedure: ```sql CREATE PROCEDURE GetEmployeeDetails @DepartmentId INT AS BEGIN DECLARE @SQL NVARCHAR(MAX); SET @SQL = 'SELECT * FROM Employees WHERE DepartmentId = @DeptId'; EXEC sp_executesql @SQL, N'@DeptId INT', @DeptId = @DepartmentId; END ``` When I call this procedure with `EXEC GetEmployeeDetails @DepartmentId = 3`, it executes without behavior, but I get no results back. However, when I hard-code the department ID directly into the SQL string, like this: ```sql SET @SQL = 'SELECT * FROM Employees WHERE DepartmentId = 3'; ``` It returns the expected list of employees in that department. I've also tried using `PRINT @SQL` before executing it to check the final query being run, and it looks correct. I suspect it has something to do with how parameters are being handled in `sp_executesql`. I’ve checked that the parameter type matches and that there are no implicit conversions that could be causing issues. Is there something I’m missing with the parameterization in this context? Any insights would be greatly appreciated! This is my first time working with Sql 3.10. What's the correct way to implement this?