|
我想知道记录是否只能插入表中而不包含记录?/ T1 B3 m; W3 H6 X* [
是否有一个查询可以做到这一点,还是我需要一个存储过程?
+ O" z- {9 Q3 z/ W* u3 E# s$ j) i / i6 M$ V! X( n8 `+ K
解决方案: ; U( a1 l% h2 m. }
你没说什么版本SQL Server。如果使用SQL Server2 v+ W5 F0 o( {9 }2 q1 }5 m6 ]
2008,则可以使用MERGE2 p4 N" ?! O4 v
注:合并通常用于注:Upsert,这是我最初认为的问题,但没有WHEN MATCHED子句且仅带WHEN NOTMATCHED在这种情况下,句子是有效的。用法示例。& k* ~ n) |7 Q; O4 w* 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);就执行成本而言,当需要执行插入操作时,两者看起来大致相等…8 o, D5 j2 g g+ {& l
链接到计划图像进行第一次操作: ~$ I6 R& E8 s3 n( Z5 \$ O6 i+ O
但在第二轮比赛中,马修的答案似乎更便宜,没有插入。我不确定是否有改进的方法。
7 T. e7 {" \" g1 }链接到计划图像以进行第二次运行
7 V: s9 i$ g+ u9 z测试脚本
9 T/ e6 q* l' `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 |
|