gpt4 book ai didi

sql-server - 获取 select 查询返回结果的模式

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:03 25 4
gpt4 key购买 nike

我们可以获取 SELECT 查询返回结果的模式吗?下面的代码:

string SQLQuery = "SELECT DISTINCT c.name 'Column Name',  t.Name 'Data type' FROM" +
" sys.columns c INNER JOIN " +
" sys.types t ON c.system_type_id = t.system_type_id" +
" LEFT OUTER JOIN " +
" sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id" +
" LEFT OUTER JOIN" +
" sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id" +
" WHERE" +
" c.object_id = OBJECT_ID('[DB].[dbo].[" + ddlTable.SelectedItem.Text + "]') AND t.name <> 'sysname'";

此代码返回指定表的列名和数据类型。我的要求是从选择查询中获取列名和数据类型,而不是直接指定表名。喜欢

  string SQLQuery = "SELECT DISTINCT c.name 'Column Name',  t.Name 'Data type' FROM" +
" sys.columns c INNER JOIN " +
" sys.types t ON c.system_type_id = t.system_type_id" +
" LEFT OUTER JOIN " +
" sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id" +
" LEFT OUTER JOIN" +
" sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id" +
" WHERE" +
" c.object_id = OBJECT_ID('SELECT col1, col2 from table(s)') AND t.name <> 'sysname'";

虽然这行不通。

最佳答案

您可以将查询结果选择到一个临时表中,并从该表中获取元数据。如果您选择这样的解决方案,您将需要确保临时表的名称在每次调用时都是唯一的,否则 information_schema View 中的元数据将在 session 之间共享。

if OBJECT_ID('tempdb..#tmp') is not null drop table #tmp

select *
into #tmp
from Customer where 1 = 0
-- select with a false predicate in order to ONLY get
-- metadata of the query and no rows of data.

select * from #tmp
-- Then select metadata from information_schema view
select COLUMN_NAME, DATA_TYPE from tempdb.information_schema.columns where TABLE_NAME like '#tmp%'

Result:
CustomerId int
CustomerType int
Name nvarchar
IsActive bit

或者,如果您愿意,可以在 C# 中更轻松地完成,这可能更不容易出错。获取查询结果集的元数据非常容易:

static void Main(string[] args)
{
string connStr = "Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True";
SqlCommand cmd = new SqlCommand("select * from Orders where 1 = 0", new SqlConnection(connStr));

SqlDataAdapter ad = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();
ad.FillSchema(ds, SchemaType.Mapped);
var metaTable = ds.Tables[0];

foreach (DataColumn col in metaTable.Columns)
{
Console.WriteLine("{0} : {1}", col.DataType, col.ColumnName);
}

}

输出:

System.Int32 : OrderId
System.Int32 : CustomerId
System.Int32 : ArticleId
System.Decimal : TotalAmount
System.DateTime : OrderDate

关于sql-server - 获取 select 查询返回结果的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21929572/

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