How to read a SQL Function Value By SQL Data Reader in C#

狂风中的少年 提交于 2019-12-25 10:08:23

问题


Hi I have a table tblRegistration which have three fields

Member_ID(int)  Left_Placement(Int) Right_Placement(int)

and one function

CREATE FUNCTION [dbo].[fnGetChildCount](
@ParentId INT
)
RETURNS INT
BEGIN
 DECLARE @ChildCount INT
 DECLARE @Left INT
DECLARE @Right INT


SET @ChildCount = 0
 IF NOT @ParentId IS NULL AND @ParentId <> 0
 BEGIN
 SET @ChildCount = 1
 SELECT @Left = Left_Placement, @Right = Right_Placement FROM tblRegistration WHERE Member_ID = @ParentId
SELECT @ChildCount = @ChildCount + [dbo].[fnGetChildCount](@Left)
 SELECT @ChildCount = @ChildCount + [dbo].[fnGetChildCount](@Right)
 END
 RETURN @ChildCount
END;

Now I use This Code

    SqlCommand cmd = new SqlCommand("SELECT Member_ID, dbo.fnGetChildCount(Left_Placement) AS [Left Count], dbo.fnGetChildCount(Right_Placement) AS [Right Count] FROM tblRegistration", con);
    dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
        while (dr.Read())
        {
            string member = dr["dbo.fnGetChildCount(Left_Placement)"].ToString();

        }
    }

To read Left Count And Right Count Which Is Not table column then

HOW CAN I READ THE LEFT COUNT(dbo.fnGetChildCount(Left_Placement) AS [Left Count]) AND RIGHT COUNT(dbo.fnGetChildCount(Right_Placement) AS [Right Count])

thank you in Advance


回答1:


Use the column aliases to retrieve the computed column values.

string leftCount = dr["Left Count"].ToString();
string rightCount = dr["Right Count"].ToString();


来源:https://stackoverflow.com/questions/15623031/how-to-read-a-sql-function-value-by-sql-data-reader-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!