Convert Oracle SQL query to Azure SQL query

偶尔善良 提交于 2021-01-29 10:02:34

问题


I have a pretty long Oracle SQL query that needs to be compatible for Azure SQL. I am new to both database types. Here is query:

MERGE INTO studies
    USING dual
    ON (study_id = :study_id)
    WHEN NOT MATCHED THEN
        INSERT (study_id, study_date)
        VALUES (:study_id, :study_date)

I am not sure USING dual would work. I read some solution saying that USING dual is not necessary in SQL Server.

I really appreciate if you can explain what this query means and how I can translate this for Azure SQL query.


回答1:


This Oracle merge query has just a WHEN NOT MATCHED clause and no WHEN MATCHED, so basically that's insert and not exists:

insert into studies(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)

This is logically equivalent to the original Oracle query.

As for your original question: SQL Server does supports its own flavor or merge statement, whose syntax is different than Oracle. You would rewrite the Oracle merge as:

merge studies as s
using (values(@study_id, @study_date)) as x(study_id, study_date)
on (s.study_id = x.study_id)
when not matched 
    then insert (study_id, study_date) values(x.study_id, x.study_date)


来源:https://stackoverflow.com/questions/63696162/convert-oracle-sql-query-to-azure-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!