当我尝试使用 sp_Executesql 时,为什么会得到类型为‘ ntext/nchar/nvarchar’的“过程期望参数‘@statement’”?

为什么我会得到这个错误

过程需要类型为‘ ntext/nchar/nvarchar’的参数‘@statement’。

当我尝试使用 sp_executesql

126175 次浏览

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

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

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