回答

收藏

只有在表中没有记录时才插入记录

技术问答 技术问答 189 人阅读 | 0 人回复 | 2023-09-14

我想知道记录是否只能插入表中而不包含记录?
# N1 ?# f+ G$ q& p是否有一个查询可以做到这一点,还是我需要一个存储过程?
0 Q& T$ W$ @4 S$ ]6 X( r; z                                                                + i6 i# Q2 `  q
    解决方案:                                                                % Z1 F) w- a+ g) k
                                                                你没说什么版本SQL Server。如果使用SQL Server* |& V2 L& @8 j+ q. q: r3 a
2008,则可以使用MERGE4 D/ E$ L4 ?! |2 N; \+ K' P% ?
注:合并通常用于注:Upsert,这是我最初认为的问题,但没有WHEN MATCHED子句且仅带WHEN NOTMATCHED在这种情况下,句子是有效的。用法示例。0 K1 S+ @- R* {7 e9 Q
CREATE TABLE #A( [id] [int] NOT NULL PRIMARY KEY CLUSTERED,[C] [varchar](200) NOT NULL)    MERGE #A AS target    USING (SELECT 3,'C') AS source (id,C)    ON (target.id = source.id)    /*Uncomment for Upsert Semantics       WHEN MATCHED THEN         UPDATE SET C = source.C */    WHEN NOT MATCHED THEN            INSERT (id,C)        VALUES (source.id,source.C);就执行成本而言,当需要执行插入操作时,两者看起来大致相等…
* c9 V8 v) b  \链接到计划图像进行第一次操作
6 y9 n: ]% C6 y8 Z" Z/ [# H但在第二轮比赛中,马修的答案似乎更便宜,没有插入。我不确定是否有改进的方法。
% ^; Z5 c( j$ O链接到计划图像以进行第二次运行* v7 n* u4 O+ G) r  B
测试脚本' g) `" u( O' U0 y% e
select * into #testtablefrom master.dbo.spt_valuesCREATE UNIQUE CLUSTERED INDEX [ix] ON #testtable([type] ASC,[number] ASC,[name] ASC)declare @name nvarchar(35)= 'zzz'declare @number int = 50declare @type nchar(3) = 'A'declare @low intdeclare @high intdeclare @status int = 0;MERGE #testtable AS targetUSING (SELECT @name,@number,@type,@low,@high,@status) AS source (name,number,[type],low,high,[status])ON (target.[type] = source.[type] AND target.[number] = source.[number] and target.[name] = source.[name] )WHEN NOT MATCHED THEN    INSERT (name,number,[type],low,high,[status])VALUES (source.name,source.number,source.[type],source.low,source.high,source.[status]);set @name = 'yyy'IF NOT EXISTS     (SELECT *    FROM #testtable    WHERE [type] = @type AND [number] = @number and name = @name)    BEGININSERT INTO #testtable(name,number,[type],low,high,[status])VALUES (@name,@number,@type,@low,@high,@status);END
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则