REPLACE INTO blastersmembers (member_id, name, member_group_id, email, joined,
/* etc. */
我没有把整件事包括在内,因为我认为它不相关。我基本上想要插入一行,如果它不存在,否则替换现有的行。
答案 0 :(得分:5)
明确地在MS SQL上存在REPLACE INTO或等效的,但您可以先执行UPDATE,如果没有更新任何内容,请执行插入操作。这看起来像这样:
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 (...)
答案 1 :(得分:2)
如果您正在使用SQL Server 2008及更高版本the MERGE command执行此操作以及更多:
-- @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);
编辑:@swasheck在未修补的服务器或旧服务器上使用某些索引视图时提到合并问题。这不应该阻止您使用MERGE,这是正确的命令使用,并且具有不需要事务的优点。