是否可以通过别名sql名称解析数据集
本文关键字:数据集 可以通过 别名 sql 是否 | 更新日期: 2023-09-27 18:16:50
所以我们有一个返回三个结果的存储过程:
SELECT * FROM Table1 WHERE Name = "bob" AS Bob
SELECT * FROM Table2 WHERE Name = "steve" AS Steve
SELECT * FROM Table3 WHERE Name = "jim" AS Jim
在c#中,我从调用中得到一个数据集:
using (SqlConnection conn = new SqlConnection("server=MySqlServer;integrated security=sspi;"))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_spaceused";
cmd.CommandTimeout = 60;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
我知道我可以得到单独的结果使用索引:
var bob = ds[0];
var steve = ds[1];
var jim = ds[2];
别名传递给c#吗?是否可以通过别名访问这些值?
@jtimperley有一个好主意,但是如果您这样做,那么无论是否返回行,您都可以对列名进行操作。
SELECT " AS TableName1, *从表1WHERE Name = "bob" AS bob
SELECT " AS TableName2, *从表二WHERE Name = "steve" AS steve
SELECT " AS TableName3, *从Table3WHERE Name = "jim" AS jim
别名传递给c#吗?
不,它没有。
是否可以通过别名访问值?
。
您只能在填充DataSet
后分配别名/TableName。基本上,您将最终失去在过程中的SQL查询中分配的别名。
不是最干净的解决方案,但您可以这样做。然后在已知列中查询您收到的表的类型。
SELECT 'Table1' AS TableName, * FROM Table1 WHERE Name = "bob" AS Bob
SELECT 'Table2' AS TableName, * FROM Table2 WHERE Name = "steve" AS Steve
SELECT 'Table3' AS TableName, * FROM Table3 WHERE Name = "jim" AS Jim