1.Merge
create table sourceTable(id int ,val varchar(20))
create table targetTable (id int,val varchar(20))
insert into targetTable values(1,'a'),(2,'b'),(3,'c')
insert into sourceTable values(3,'c'),(4,'d'),(4,'d')
----
MERGE INTO TargetTable AS T
USING SourceTable AS S
ON T.id=S.ID
WHEN MATCHED
THEN
UPDATE SET t.Val=s.val
WHEN NOT MATCHED
THEN INSERT VALUES(s.id,s.val)
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
----SqlServer 递归查询
WITH TEST_CTE
AS
(
SELECT C.id,C.FistName,C.ParentID,C.FistID,
CAST(C.FistID as nvarchar(4000)) AS PATH
FROM Test1 C WHERE C.parentID=0
UNION ALL
SELECT CTBIE.id,
CTBIE.FistName,
CTBIE.ParentID,
CTBIE.FistID,
CTE.PATH+'->'+Cast(CTBIE.FistID as nvarchar(4000)) PATH
FROM Test1 CTBIE
INNER JOIN TEST_CTE CTE ON CTBIE.ParentID=CTE.FistID
)
SELECT * FROM TEST_CTE
--限制递归次数
OPTION(MAXRECURSION 10)
---扩展:构造递归路径
WITH TEST_CTE
AS
(
SELECT C.id,C.FistName,C.ParentID,C.FistID FROM Test1 C WHERE C.parentID=0
UNION ALL
SELECT CTBIE.id,CTBIE.FistName,CTBIE.ParentID,CTBIE.FistID FROM Test1 CTBIE
INNER JOIN TEST_CTE CTE ON CTBIE.ParentID=CTE.FistID
)
SELECT * FROM TEST_CTE
--限制递归次数
OPTION(MAXRECURSION 10)
-----快速找出数据库的性能问题之:缺失索引 &无用的索引
SELECT TOP 100
equality_columns ,
inequality_columns ,
included_columns ,
statement ,
avg_total_user_cost ,
avg_user_impact
FROM sys.dm_db_missing_index_details AS mid
INNER JOIN sys.dm_db_missing_index_groups mig ON mig.index_handle = mid.index_handle
INNER JOIN sys.dm_db_missing_index_group_stats migs ON mig.index_group_handle = migs.group_handle
ORDER BY avg_total_user_cost DESC;