简体   繁体   中英

Filla Datatable with a stored procedure result

I need to fill a DataTable with the results from the following stored procedure:

BEGIN
    -- Simply example
    IF OBJECT_ID('dbo.canela', 'U') IS NOT NULL 
      DROP TABLE dbo.canela;    

    CREATE TABLE canela
    (
        [ColA] VARCHAR(200),
        [ColB] VARCHAR(100),
        [ColC] VARCHAR(100)
    );

    INSERT INTO canela([ColA], [ColB], [ColC]) 
    VALUES (@i + 12, 'Io', 'tu')

    SELECT * 
    FROM canela 
END

Here's my code:

public DataTable GetTableSqlFromSp(string sql)
{
    ErrorListMessages.ClearErrors();

    DataTable dt = null;

    if (ConnectionOpen())
    {
        try
        {
            using (OleDbCommand cmd = new OleDbCommand(sql, Cnn))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                {
                    da.Fill(dt = new DataTable());
                }
            }
        }
        catch (Exception ex)
        {
            ErrorListMessages.SetInternalError(ex, string.Format("GetTableSql({0})", sql));
            return null;
        }
    }
    return dt;
}

And the SQL:

EXEC Antani @i = '8';

I got an error

Syntax error or access violation

but I don't know why. If I fire my stored procedure directly in SQL Server, all works fine.

Use System.Data.SqlClient.

var dt = new DataTable();
var cmd = new SqlCommand("EXEC Antani @i = '8'", Cnn);
cmd.CommandType = CommandType.Text;
using (var rdr = cmd.ExecuteReader())
{
  dt.Load(rdr);
}

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