gpt4 book ai didi

sql - 如何转换选择查询

转载 作者:行者123 更新时间:2023-12-04 14:27:17 26 4
gpt4 key购买 nike

我有 DDL:

drop table names
drop table salary

create table names(
id int,
name1 varchar(50),
char1 varchar(50),
char2 varchar(50))

insert into names values (1,'name1','char1','chara'),
(2,'name2','char2','charb'),
(3,'name3','char3','charc'),
(4,'name4','char4','chard'),
(5,'name5','char5','charf');

create table salary(
id int,
salary int,
bonus int,
oldsalary int)

insert into salary values (1,500,245,354),
(2,600,345,246),
(3,60,365,334),
(4,55,545,364),
(5,25,345,374);

并且有许多 SQL 查询(其中之一)

    SELECT n.name1,
s.salary,
s.bonus,
( s.bonus + s.salary ) AS Sumsalary
FROM names n
INNER JOIN salary s
ON n.id = s.id

我想编写选择查询,从 SQL 查询中使用的表中检索所有字段名,除以此选择查询中的使用情况,并在屏幕截图中提到一些附加信息。

我想从此查询中检索的数据格式:**enter image description here

最佳答案

如果您有权访问系统 View ,您可以获得用于查询的表和列的列表:

;WITH XMLNAMESPACES ('http://schemas.microsoft.com/sqlserver/2004/07/showplan' AS ns)
SELECT DISTINCT st.TEXT AS QueryText,
C.value('./@Table', 'varchar(50)') As Tab,
C.value('./@Column', 'varchar(50)') As Col
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st
CROSS APPLY query_plan.nodes('//ns:ColumnReference') as T(C)
WHERE cp.ObjType = 'Adhoc' AND
St.Text Like '%s.bonus%' AND
st.Text Not Like '%WITH XMLNAMESPACES%' AND
C.value('./@Table', 'varchar(50)') IS NOT NULL

结果如下:

QueryText            Tab       Col
SELECT n.name1, ... [Names] id
SELECT n.name1, ... [Names] name1
SELECT n.name1, ... [Salary] bonus
SELECT n.name1, ... [Salary] id
SELECT n.name1, ... [Salary] salary

然后,您可以使用这些结果作为链接到 sys.columns 的一种方式,以确定缺少哪些列等。

关于sql - 如何转换选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com