Solution to sp_executesql's error in using complex Unicode expressions

Source: Internet
Author: User

Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '+ '.

When you try to execute the following code, you will receive the above error message.
Copy codeThe Code is as follows:
DECLARE @ MyName NVARCHAR (100)
DECLARE @ FieldName SYSNAME = n' name'
EXECUTE sp_executesql n' select top 1 @ OutputName = ['+ @ FieldName +'] FROM [dbo]. [Member] ',
N'@ OutputName NVARCHAR (100) output ',
@ MyName OUTPUT;
SELECT @ MyName


The problem is that more complex Unicode expressions are not allowed (for example, using the + operator to connect two strings ). See http://technet.microsoft.com/zh-cn/library/ms188001.aspx
[@ Statement =] statement
Unicode string that contains a Transact-SQL statement or batch processing. Statement must be a Unicode constant or a Unicode variable. More complex Unicode expressions are not allowed (for example, using the + operator to connect two strings ). Character constants are not allowed. If a Unicode constant is specified, N must be used as the prefix. For example, the Unicode constant n'sp _ who 'is valid, but the character constant 'SP _ who' is invalid. The size of the string is limited only by the memory of the available database server. In a 64-bit server, the string size is limited to 2 GB, that is, the maximum nvarchar (max) size.

To solve the problem, you can DECLARE a variable in the following code: DECLARE @ SQL NVARCHAR (MAX). assign a value to the variable for the SQL statement with the dynamic data name, table name, or field, use this variable to pass in sp_executesql.
Copy codeThe Code is as follows:
DECLARE @ MyName NVARCHAR (100)
DECLARE @ FieldName SYSNAME = n' name'
DECLARE @ SQL NVARCHAR (MAX) = n' SELECT TOP 1 @ OutputName = ['+ @ FieldName +'] FROM [dbo]. [Member]'
EXECUTE sp_executesql @ SQL,
N'@ OutputName NVARCHAR (100) output ',
@ MyName OUTPUT;
SELECT @ MyName


The problem can be easily solved.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.