SQL Server stored procedure implementation and stitching SQL attention point _mssql

Source: Internet
Author: User

The problem I met yesterday was to execute a paragraph. Changes to the field state of a different table according to the variable tablename. Because of the server, I could not write SQL directly in the data access layer, so I had to pull 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 write? And you see:

declare @tableName nvarchar (m),
@field1 int,
@field2 nvarchar,
@id int
declare @sql n varchar (max)
set @sql = ' Update ' + @tableName + ' Set field1= ' + @field1 + ', field2= ' + @field2 + ' where id= ' + @id

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

So what is the exact value of this error? In fact, in the concatenation of SQL, this @sql if a string type, all the variables must also be expressed in string, my upper @field1 and @id are int, so to convert to nvarchar type, and a variable (field) of type nvarchar must be enclosed in single quotes; note: In SQL, single quotes are expressed in two single quotes

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

 
 

This question is actually very simple, but because my knowledge of SQL is very insufficient, so I record here to consolidate myself.

The above is a small set of SQL Server to introduce the implementation of stored procedures and stitching the attention point of SQL, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.