I have a SQL query I need to understand and translate to SQL Server query. Here is SQL query:
MERGE INTO study_event
USING dual
ON (study_id = :study_id)
WHEN NOT MATCHED THEN
INSERT (study_id, study_date)
VALUES (:study_id, :study_date)
From how I understand, this means if study_event table doesn't have given study_id, I am inserting row to study_event table with given study_id and study_date. Is this correct?
I am trying to create SQL Server query that will do the same operation. From stack overflow, this is what I found:
INSERT INTO study_event(study_id, study_date)
SELECT x.*
FROM (VALUES(@study_id, @study_date)) as x(study_id, study_date)
WHERE NOT EXISTS (SELECT 1 FROM studies s1 WHERE s1.study_id = x.study_id)
I think I understand this query but I am not sure what SELECT x.*
means. Would this query work and what does x.* mean?
x
refers to the alias that the values()
subquery creates, here:
FROM (VALUES(@study_id, @study_date)) as x(study_id, study_date)
This creates a derived table with one row and two columns study_id
and study_date
.
So basically x.*
gives you the entire row from x
, which contains the two original parameters to the query, @study_id
and @study_date
.
Disclaimer: I answered the original question!