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!