简体   繁体   English

如何将该MySQL查询编写为T-SQL?

[英]How can I write this MySQL query as T-SQL?

REPLACE INTO blastersmembers (member_id, name, member_group_id, email, joined,
/*  etc.  */ 

I haven't included the whole thing because I don't believe it to be relevant. 我没有将整个内容包括在内,因为我不认为这是相关的。 I basically want to insert a row if it doesn't exist, otherwise replace the existing row. 我基本上想插入一行(如果不存在),否则替换现有的行。

REPLACE INTO or an equivalent doesn't exist on MS SQL explicitly, but you can do an UPDATE first, and if that did not update anything, do an insert. 在MS SQL上没有REPLACE INTO或等效项,但是您可以先执行UPDATE,如果没有更新,请执行插入操作。 That would look something like this: 看起来像这样:

update blastersmembers set name = @name, member_group_id = @member_group_id, email = @email, joined = @joined, ... 
where member_id = @member_id
if @@rowcount = 0
insert into blastersmembers (member_id, name, member_group_id, email, joined, ...) values (...)

Credit to: Insert Update stored proc on SQL Server 归功于: 在SQL Server上插入更新存储的proc

If you're using SQL server 2008 and later the MERGE command does that and more: 如果您使用的是SQL Server 2008及更高版本, 则MERGE命令可以执行以下操作:

-- @member_id, @member_group_id are the ids of the record you want to match

merge blastermembers as target
    using (select @member_id, @member_group_id) as source (member_id, member_group_id)
    on source.member_id = target.member_id 
           and source.member_group_id = target.member_group_id
    when matched then
        update set name = @name -- etc
    when not matched then
        insert (member_id, name, member_group_id) 
                   values (source.member_id, name, source.member_group_id);

Edit: @swasheck mentions problems with merge when using some indexed views in unpatched servers, or on old servers. 编辑:@swasheck提到了在未修补的服务器或旧服务器上使用某些索引视图时合并的问题。 This should not prevent you from using MERGE which is the right command to use and has the advantage of not requiring a transaction. 这不应阻止您使用MERGE,它是正确的命令,并且具有不需要事务处理的优点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM