【问题标题】:How to handle inline table-valued function that returns a table using ado.net如何使用 ado.net 处理返回表的内联表值函数
【发布时间】:2016-01-25 05:47:54
【问题描述】:

我已经在 sql 中实现了内联表值函数。我正在尝试使用 ado.net 读取从 C# 中的内联表值函数返回的表值。请帮忙。我在这里附上代码。

Sql函数:-

CREATE FUNCTION fun 
(   
    @lname varchar(50)
)
RETURNS TABLE 
AS
RETURN 
(
    select fp.accntname,ld.BU,fp.salesop,idt.isdormant from legacy_system as ls
inner join fourth_page as fp on ls.accountname=fp.accountname
inner join linked as ld on fp.productid=ld.productid
inner join isdormant as idt on idt.productid=ld.productid
inner join legacy_system as l on ls.productid=idt.productid
where l.legacyname in(@lname)
)
GO

C#代码:-

 [HttpPost]
            public void call_stored_procedure(List<string> lyname)
            {
                Console.WriteLine(lyname);
                string dogCsv = string.Join(",", lyname.Select(i => "'" + i + "'"));
                Console.WriteLine(dogCsv);
                using (SqlConnection connection = new SqlConnection("data source=.; database=Srivatsava; integrated security=SSPI"))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "select dbo.fun(@lname)";
                        command.Parameters.AddWithValue("@lname", dogCsv);
                        command.CommandType = CommandType.Text;
                        String s=command.ExecuteScalar().ToString();
                        Console.WriteLine(s);
                        connection.Close();
                    }
                }

            }

【问题讨论】:

    标签: c# asp.net sql-server asp.net-mvc ado.net


    【解决方案1】:

    表值函数返回一个表,以便读取命令文本应为的结果

    command.CommandText = "select * from dbo.fun(@lname)";
    

    现在您正在使用 ExecuteScalar() 函数来执行您的命令。

    来自 MSDN - ExecuteScalar()

    执行查询,并返回第一行的第一列 查询返回的结果集。额外的列或行是 忽略。

    因此,即使您的函数返回包含多列的记录集,也只会返回第一行的第一列。

    如果需要读取表值函数返回的完整记录集,需要使用ExecuteReader()函数。

    ExecuteReader()

    将 CommandText 发送到 Connection 并构建 SqlDataReader。

    【讨论】:

      【解决方案2】:

      以下所有链接都是related to your question .. 它已经解决了.. 所以请before post any question .. 请看看它是否已经回答/解决了..

      Calling SQL Defined function in C#

      How can I call a SQL function in C#?

      Calling SQL Functions directly from C#

      【讨论】:

        猜你喜欢
        • 2023-03-09
        • 1970-01-01
        • 2014-01-07
        • 2015-03-08
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-07
        相关资源
        最近更新 更多