SQL Server 高级SQL
查询view 的列和列数据类型
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'view name'
树
1. 所有的子树
WITH SubTree AS ( SELECT tt.ID as SubTreeRoot, tt.ID FROM TreeTable tt UNION ALL SELECT st.SubTreeRoot, tt.ID FROM TreeTable tt INNER JOIN SubTree st ON st.ID = tt.ParentID ) SELECT st.SubTreeRoot, st.ID FROM SubTree st
2.获取某个子树
WITH SubTree AS ( SELECT tt.ID as SubTreeRoot, tt.ID FROM TreeTable tt WHERE tt.ID= @OneOfIDs UNION ALL SELECT st.SubTreeRoot, tt.ID FROM TreeTable tt INNER JOIN SubTree st ON st.ID = tt.ParentID ) SELECT st.SubTreeRoot, st.ID FROM SubTree st
3.获取叶子结点
SELECT * FROM TreeTable a WHERE NOT Exists(SELECT 1 FROM TreeTable b WHERE a.ID = b.ParentID)
查询表的外键
SELECT f.name AS foreign_key_name ,OBJECT_NAME(f.parent_object_id) AS table_name ,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS constraint_column_name ,OBJECT_NAME (f.referenced_object_id) AS referenced_object ,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS referenced_column_name ,is_disabled ,delete_referential_action_desc ,update_referential_action_desc FROM sys.foreign_keys AS f INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id WHERE f.parent_object_id = OBJECT_ID('HumanResources.Employee');
SELECT r.session_id ,st.TEXT AS batch_text ,SUBSTRING(st.TEXT, statement_start_offset / 2 + 1, ( ( CASE WHEN r.statement_end_offset = - 1 THEN (LEN(CONVERT(NVARCHAR(max), st.TEXT)) * 2) ELSE r.statement_end_offset END ) - r.statement_start_offset ) / 2 + 1) AS statement_text ,qp.query_plan AS 'XML Plan' ,r.* FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st CROSS APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp ORDER BY cpu_time DESC