简体   繁体   中英

How do I return multiple rows of parameter data with C#

I'm using C# to extract data to T-SQL parameters, the query is:

DECLARE @Param1 INT, @Param2 NCHAR(50), @P3 REAL, @P4 BIT
SELECT @Param1 = [idx]
      ,@Param2 = [data]
      ,@P3 = [itgetsreal]
      ,@P4 = [wazzup]
    FROM [T].[dbo].[temp];

Running from MS SQL Server Management Studio yields a predictable one line dataset, the last. My C# code creates output parameters:

public class ParamData 
{   //  query has executed, return parameter data in class properties
    public string[] names; public Object[] vals; public bool success = false;
    public ParamData(SqlCommand cmd)
    {
        if (cmd == null) {
            err = "SqlCommand \"cmd\" may not be NULL";
            errcode = -1; errdata = ""; errsrc = "ParamData(SqlCommand cmd)"; }
        else {
            if (cmd.Parameters == null) { err = "\"SqlCommand.Parameters\" may not be NULL";
                errcode = -1; errdata = cmd.CommandText; errsrc = "ParamData(SqlCommand cmd)"; }
            else { 
                try {err = ""; errcode = 0; errdata = ""; errsrc = ""; 
                    int cnt = cmd.Parameters.Count;
                    if (cnt > 0) {
                        names = new string[cnt]; vals = new object[cnt];
                        for (int i = 0; i < cnt; i++)
                        {
                            names[i] = cmd.Parameters[i].ParameterName;
                            vals[i] = cmd.Parameters[i].Value;
                        }
                    }
                    success = true;
                }
                catch (SqlException ex) {
                    err = ex.Message; errcode = ex.Number;
                    errdata    = String.Format("Parameters name/val assignment: Query: \"{0}\"",
                                                    cmd.CommandText);
                    errsrc     = "ParamData(SqlCommand cmd)";} 
            }
        }
    }
}

How do I create a SqlReader type object where I can extract each row of the dataset and not only the last?

BTW: I've got means already to bring in the data without parameters but am constrained to provide a legacy compatibility and can't yet replicate the original function.

You can't return multiple rows of T-SQL variables/parameters. Parameters only hold the last value.

The comments are spot on - one needs to return datasets ( not through parameters ) to obtain multiple rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM