Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?
Asked Answered
D

3

99

Why do I get this error

Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.

when I try to use sp_executesql?

Demilitarize answered 30/4, 2010 at 10:41 Comment(1)
How are you trying to execute it? In T-SQL? From a program? Are you passing the required "@statement" parameter?Finnigan
B
225

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
Baber answered 30/4, 2010 at 10:47 Comment(1)
This does work, but the other answer (from Daniel Renshaw) is WAY more useful, most of the time. (since it doesn't need the pointless variable declaration)Theodicy
K
24

The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:

DECLARE @SQL NVARCHAR(100) 
SET @SQL = N'SELECT TOP 1 * FROM sys.tables' 
EXECUTE sp_executesql @SQL
Knucklebone answered 30/4, 2010 at 10:51 Comment(0)
C
0

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

Crabber answered 14/2, 2020 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.