【发布时间】:2019-04-26 01:19:49
【问题描述】:
我在 .net 中按名称运行存储过程,并将数据作为 JSON 返回到我的前端
如果我的存储过程是
SELECT name from employees
我得到一个 tablename = "Table1" 的表
所以我的 JSON 是 {Table1 : [ {row1stuff},{row2stuff}]}
我想在我的程序中定义表名。
我现在在做
SELECT 'names'
SELECT name from employees
在我的 c# 中,我遍历第一个表的值并命名其他表
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt); //dt is a dataset
//start at 1 since the first table is the tablenames table
for (int i = 1; i < dt.Tables.Count; i++)
dt.Tables[i].TableName = dt.Tables[0].Rows[0].ItemArray[i-1].ToString();
//get rid of the first table
dt.Tables.RemoveAt(0);
return JObject.FromObject(dt);
它现在可以工作了,我的 json 是 {names:[{row1},{row2}...]}
如果我能做到就太好了
SELECT name from employees as names
(但这不会在sp返回的内容中设置表名,只是为sql设置)
为了清楚起见,我的一些存储过程返回多个结果集,所以我这样做了
SELECT 'Employees','Cars','Websites'
SELECT * FROM employees
SELECT * FROM cars
SELECT * from sites
所以我得到了 json
{Employees:[{emp1},{emp2}...], Cars:[{car1}], Websites:[{site1}, {site2}]}
这是完美的,但让 SP 奇怪的是我如何在顶部选择选择.. 当你只看 sp 时并不是很明显
【问题讨论】:
-
没有关于查询表名称的信息从存储过程传回,从 n 个连接表中选择会返回什么?
Table1是 .netDataTable类的工件。输出参数可以替代SELECT。 -
@AlexK。我不希望它从我正在查询的表中决定表名,这将是我必须输入的内容(所以连接无关紧要)。 “Table1 is an artifact...”是我害怕的:(我使用的是输出参数,但它在 SP 中比在 SELECT 中更麻烦。不过谢谢!-有时很高兴听到它可以没有完成,所以你不再担心它。
标签: c# sql-server stored-procedures