SQL-dynamic SQL, connection string and variable issues

Source: Internet
Author: User

 

Now we need to improve the paging storage process, because we have added the date-based get posts, sort by fields, and select sorting methods. In this case, you need to set some variables to receive these values from the application and connect them with the select and where strings.
Code:
Declare @ chengji int, @ SQL varchar (800)
Select @ chengji = 70
Set @ SQL = 'select * from Stu where score = '+ @ chengji
Print @ SQL

But when the problem arises, it always prompts that the varchar value 'select * from Stu where score = 'fails to be converted to the Data Type Int.

If changed:
Declare @ chengji varchar (800), @ SQL varchar (800)
Select @ chengji = 'A'
Set @ SQL = 'select * from Stu where score = ''' + @ chengji + ''''
Print @ SQL
You can.

========================================================== ======================
After verification: The cause and solution are as follows:

Because @ chengji is an integer, the integer cannot be directly connected to the character type with the plus sign (+), and must be converted to the character type before connection.
Try:
Declare @ chengji int, @ SQL varchar (800)
Select @ chengji = 70
Set @ SQL = 'select * from Stu where score = '+ rtrim (@ chengji)
Print @ SQL

Normal
Declare @ chengji int, @ SQL varchar (800)
Select @ chengji = 70
Set @ SQL = 'select * from Stu where score = '+ Cast (@ chengji as varchar (10 ))
Print @ SQL

Normal
Declare @ chengji int, @ SQL varchar (800)
Select @ chengji = 70
Set @ SQL = 'select * from Stu where score = '+ convert (varchar (10), @ chengji)
Print @ SQL
Normal

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.