Blog Pages

sp_executesql ERROR: Procedure expects parameter '@parameters' of type 'ntext/nchar/nvarchar'

Error:
EXEC sp_executesql N'SELECT @x', '@x int', @x = 2
--or:
EXEC sp_executesql 'SELECT @x', N'@x int', @x = 2

This error message will be displayed:
Msg 214, Level 16, State 3, Procedure sp_executesql, Line 1
Procedure expects parameter '@parameters' of type 'ntext/nchar/nvarchar'.

Explanation:
The first and the second parameters of sp_executesql are Unicode - nvarchar/ntext (depend on the MSSQL version).
varchar is not valid!

Solutions:
--1.
EXEC sp_executesql N'SELECT @x', N'@x int', @x = 2

-- 2.
DECLARE @stmt nvarchar(max), @params nvarchar(max)
SET @stmt = 'SELECT @x' -- @stmt was declared as nvarchar, so the N is not required
SET @params = '@x int' -- @params was declared as nvarchar, so the N is not required
EXEC sp_executesql @stmt, @params, 2

3 comments: