Home > database >  After a property only constraint in Sql server, insert the new data, the key is constant, the value
After a property only constraint in Sql server, insert the new data, the key is constant, the value

Time:05-26

For example: id: 1; Name: zhang SAN; Value1:57; Value2:54; Value3:99
The only constraint name, insert zhang SAN again, value1 + value1 '
Or value1 + value1, value2 + value2, value3 + value3 '
Can accumulate a value alone or all of the value, how to realize respectively?

CodePudding user response:

The duplicate of this problem, a bit of a mysql key on the meaning of the update (there is no insert, update)
Mysql case:
 insert into test_tbl (id, Dr) 
Values (1, '2'), (2, '3'),... (x, 'y')
On the duplicate key update Dr=values (Dr);


SQL server, is a little more complicated
Use the merge into can
Case:
 MERGE INTO dbo. TargetTable AS T 
USING dbo. SourceTable AS S
ON T.I D=S.I D
The WHEN MATCHED - WHEN it On the back of the T.i d=S.i d, the data in the target table is updated
THEN UPDATE the SET (DESC)=t. s./DESC
WHEN NOT MATCHED -- target table no ID, in the source table, these rows inserted into the target table
THEN INSERT VALUES (S.I D, s. (DESC))
WHEN is NOT MATCHED BY the SOURCE - the target table and data line of the SOURCE table does NOT exist, then delete these lines in the target table
THEN DELETE;

CodePudding user response:

Direct writing SQL server if it is not convenient, can consider to use table insert trigger + merge into, this is no problem
  • Related