MSSQL stored procedure realizes stitching SQL's attention point

Source: Internet
Author: User
Tags mssql

The problem I ran into yesterday was the execution of a change in the field state of a different table based on the variable tablename. Because of the server, I couldn't write SQL directly at the data access layer, so I had to pull it out and put it in the stored procedure.

There is a problem here, I spent a long time to good grasp!

is actually a very simple SQL statement:

Update table1 Set field1=value1,field2 = value2 WHERE id = ID

What did I look like? Everyone and see:

    Declare @tableName nvarchar( -),@field1 int,@field2 nvarchar,@id int    Declare @sql nvarchar(Max)Set @sql = 'Update'+@tableName+'Set field1='+@field1+', field2='+@field2+'where id='+@id    exec @sql

Students who have experience in this area must know that this is obviously wrong, SQL will report an exception, said nvarchar converted to int type

So what is the exact value of this error? In fact, when splicing SQL, this @sql if a string type, all the variables must also be represented by a string, I above the @field1 and @id is an int, so to convert to nvarchar type, and a variable of type nvarchar (field) must be enclosed in single quotation marks; Note: single quotes in SQL are represented by two single quotes

So after modification, the correct splicing of the SQL code is:

  

Set @sql='Update'+@tableName+ 'Set field1='+cast(@field1  as varchar)+', field2=" "+@field2+" "where id='+CAST(@id  as varchar)

This problem is very simple, but because my knowledge of SQL is very insufficient, so here record to consolidate their

  

MSSQL stored procedure realizes stitching SQL's attention point

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.