¿Qué es USAR en la sintaxis de SQL Server 2008 MERGE?
Jacob hizo la pregunta perfecta:Dame elMERGE
sintaxis.
Cada respuesta por ahí salta inmediatamente al caso más complicado que se pueda imaginar; oscureciendo la sintaxis con extraña confusión.
Marc diouna respuesta:
MERGE
member_topic AS target
USING
someOtherTable AS source
ON
target.mt_member = source.mt_member
AND source.mt_member = 0
AND source.mt_topic = 110
WHEN MATCHED THEN
UPDATE SET mt_notes = 'test'
WHEN NOT MATCHED THEN
INSERT (mt_member, mt_topic, mt_notes) VALUES (0, 110, 'test')
;
Viendo esta respuesta, estoy tan confundido como Jacob estaba:
No tengo alguna otra tabla
Marc sugirió quesomeOtherTable
es un valor de marcador de posición ficticio: no importa que no tenga esa tabla.
Lo intento, y SQL Serverhace quejar
Nombre de objeto no válido 'someOtherTable'.
Eso me deja luchando por entender lo que elUSING
enUSING foo
espara Si no es importante (excepto realmente importante).
Que esUSING
usando cuando esta usandofoo ¿Cuándo uso la sintaxis de SQL Server 2008 MERGE?
¿Cuál es la sintaxis de UPSERT utilizando MERGE?
IF (rowExists)
UPDATE Users SET Firstname='Ian', LastName='Boyd' WHERE Username='iboyd'
ELSE
INSERT INTO Users (UserGUID, Username, FirstName, LastName, AuthenticationMethod)
VALUES ('{77410DC5-7A3E-4F1A-82C6-8EFB3068DE66}', 'iboyd', 'Ian', 'Boyd', 'Windows')
se convierte (código exacto que probé):
begin transaction
MERGE
Users
USING
foo
ON
Users.UserName = foo.UserName
WHEN MATCHED THEN
UPDATE SET Firstname = foo.FirstName, Lastname = foo.LastName
WHEN NOT MATCHED THEN
INSERT (UserGUID, Username, FirstName, LastName, AuthenticationMethod)
VALUES ('{77410DC5-7A3E-4F1A-82C6-8EFB3068DE66}', 'iboyd', 'Ian', 'Boyd', 'Windows')
; --A MERGE statement must be terminated by a semi-colon (;).
rollback
Msg 208, Level 16, State 1, Line 3
Invalid object name 'foo'.
?
Con unUsers
Tabla que contiene las columnas:
UserGUID uniqueidentifier
Username varchar(50)
FirstName varchar(50)
LastName varchar(50)
AuthenticationMethod varchar(50)
Actualizar:
USING <table_source>
Dóndetable_source
es:
table_or_view_name [ [ AS ] table_alias ] [ <tablesample_clause> ]
[ WITH ( table_hint [ [ , ]...n ] ) ]
| rowset_function [ [ AS ] table_alias ]
[ ( bulk_column_alias [ ,...n ] ) ]
| user_defined_function [ [ AS ] table_alias ]
| OPENXML <openxml_clause>
| derived_table [ AS ] table_alias [ ( column_alias [ ,...n ] ) ]
| <joined_table>
| <pivoted_table>
| <unpivoted_table>
Dóndejoined_table
es:
indefinido
Dóndepivoted_table
es:
indefinido
Dóndeunpivoted_table
es:
indefinido