C# Paginate SQL result from a proc call - c#

I have the following method that calls a proc in my database and returns the results into a dataset. The dataset is then used to populate a table I render using MVC & cshtml.
The method is:
public DataSet CallProcToDataSet(string procName)
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
}
}
}
return ds;
}
This works fine, however what I want is to have some way of paginating the results so that only 10 at a time are displayed. What is the best way for me to achieve this that doesn't involve any changes to the proc calls?

You can use this overload of the Fill method
public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables);
(link: https://msdn.microsoft.com/en-us/library/0z5wy74x(v=vs.110).aspx)
This way you will only return a subset of the records without modifying your stored procedure.
Example (MSTest)
[TestMethod]
public void TestMethod1()
{
DataSet ds = new DataSet();
var procName = "sp_server_info";
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
var tblName = "result";
var tbls = new[] { ds.Tables.Add(tblName) };
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(0, 10, tbls);
}
}
}
Assert.AreEqual(tbls[0].Rows.Count, 10);
}

Try following :
DataSet ds = new DataSet();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i += 10)
{
DataTable pageTable = dt.AsEnumerable().Where((x, n) => (n >= i) && (n < i + 10)).CopyToDataTable();
}

Related

SqlDataAdapter handle error - object is not created

I have this error:
Invalid object name 'sap.AfdelingsrapportACTUAL'.
Which is because this table is not created yet.
I need to implement a check in my SqlDataAdapter - so if is null or doesnt get anything it moves on. But i really doesnt know how to.
I think it should be around my SqlDataAdapter but i could be wrong
Code
DataTable sqldt = new DataTable();
string sqlQuery = #"Select * from " + table;
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, sqlcon);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(sqldt);
}
What i think it should look like:
public static bool CompareDataTables(DataTable dt, string table, string connectionString)
{
DataTable sqldt = new DataTable();
string sqlQuery = #"Select * from " + table;
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, sqlcon);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
if (da == "doesnt have any table")
{
return true;
}
else
{
da.Fill(sqldt);
}
}
int sqlCols = sqldt.Columns.Count;
int excelCols = dt.Columns.Count;
if (excelCols == sqlCols)
{
return false;
}
else return true;
}
One way would be first check for the existence of the data table.
follow the sample given here:
Check if table exists in SQL Server

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

Must declare a scalar variable.?

I have to display bar chart using ajax extender tool. I have to display information on chart when I am selecting one value from drop down list. But it shows "Must declare a scalar variable" error. Please help me.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = string.Format("select Debit, Credit, Year From aTable where Name=#Name", ddlCountries.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} Order Distribution", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
In this line
string query = string.Format(#"select Debit, Credit, Year
From aTable where Name=#Name",
ddlCountries.SelectedItem.Value);
you have a parameter placeholder #Name but you don't add the required parameter to the SqlCommand that executes the sql. This produces the error that you see.
(By The way, string.Format requires the placeholder in the form {0}, but also if you fix that problem it is still wrong because you leave open the door to Sql Injection)
Fixing it requires a change in your GetData function.
You need to add an (optional) parameter array as another argument
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if(prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
And now, when you call that method, you could write
string query = "select Debit, Credit, [Year] From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#Name", SqlDbType.NVarChar).Value =
ddlCountries.SelectedItem.Value.ToString());
DataTable dt = GetData(query, prms);
Notice also that I have put the field Year between square brackets. Year is the name of a T-SQL Function and you should use this trick to avoid to confuse the SQL Parser

using WHERE in my Insert query statement

string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\user\Documents\Visual Studio 2010\Projects\Timetable\Timetable\bin\Debug\timetabledata.accdb";
//create the database query
string query = "SELECT * FROM relation";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
// create the DataSet
DataSet ds = new DataSet();
// create the adapter and fill the DataSet
OleDbDataAdapter adapter;
adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);
int f = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i < f; i++)
{
// create the database query
string query1 = "SELECT * FROM [time] Where classid= '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
DataSet ds1 = new DataSet();
OleDbDataAdapter adapter1;
adapter1 = new OleDbDataAdapter(query1, conn);
adapter1.Fill(ds1);
MessageBox.Show(ds1.Tables[0].Rows[0].ItemArray[0].ToString());
}
the result that i get not true in message box that i want the id of all rows having the same classid but in message box that i use just to verification before o continue i see the id of time table without be consider where
Shouldn't this part be changed from...
string query1 = "SELECT * FROM [time] Where classid+ '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
to...
string query1 = "SELECT * FROM [time] Where classid = '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
You seem to be using a plus symbol (+) instead of equals (=).
Give this a shot:
public DataSet GetRelations()
{
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
using (var adapter = new OleDbDataAdapter("SELECT * FROM [relation]", connection))
{
var results = new DataSet();
adapter.Fill(results);
return results;
}
}
}
public DataSet GetTimeResults()
{
DataSet dsRelations = GetRelations();
var dsResults = new DataSet();
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
foreach (DataRow row in dsRelations.Tables[0].Rows)
{
using (var command = new OleDbCommand("SELECT * FROM [time] Where classid = ?", connection))
{
// not entirey sure what the value of row.ItemArray[2] is ?
command.Parameters.Add(row.ItemArray[2]);
using (var adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dsResults);
}
}
}
}
return dsResults;
}
Just invoke it and use it as you see fit:
public void Test()
{
DataSet dsTimeResults = GetTimeResults();
// Do whatever you need with the results
}

SQLCommand syntax error

I am writing to request some help on my c# syntax. I keep getting syntax in "sda.Fill(dt);" and I can not figure out the reason why.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select distinct Price_type from Price";
DataTable dt = GetData(query);
ddlPrice.DataSource = dt;
ddlPrice.DataTextField = "Price_type";
ddlPrice.DataValueField = "Price_type";
ddlPrice.DataBind();
ddlPrice2.DataSource = dt;
ddlPrice2.DataTextField = "Price_type";
ddlPrice2.DataValueField = "Price_type";
ddlPrice2.DataBind();
ddlPrice2.Items[1].Selected = true;
}
}
protected void Compare(object sender, EventArgs e)
{
string query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice.SelectedItem.Value);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice.SelectedItem.Value, Data = y });
query = string.Format("select price, date from Price where Price_type = '{0}' order by date)", ddlPrice2.SelectedItem.Value);
dt = GetData(query);
y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
LineChart1.Series.Add(new AjaxControlToolkit.LineChartSeries { Name = ddlPrice2.SelectedItem.Value, Data = y });
LineChart1.CategoriesAxis = string.Join(",", x);
LineChart1.ChartTitle = string.Format("{0} and {1} Order Distribution", ddlPrice.SelectedItem.Value, ddlPrice2.SelectedItem.Value);
LineChart1.Visible = true;
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
date might be a reserved keyword, depending of the version you use. Write [date] instead. And this
"select price, date from Price where Price_type = '{0}' order by date)"
should be
"select price, date from Price where Price_type = '{0}' order by date"
You can try with this code
using (var con = new SqlConnection(constr))
{
using (var cmd = new SqlCommand(query))
{
using (var sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
There's nothing syntactically wrong with your GetData() method as shown in your original post. You might try commenting out the entire body of the method and then start uncommenting things one at a time to isolate the actual problem.
But it apparently seems that you don't have a syntax error: you have invalid SQL. The SQL you are trying to execute is:
select price, date from Price where Price_type = '{0}' order by date)
It has two things wrong with it:
The closing (right) parenthesis at the end is your syntax error, and
the parameter should not be enclosed in quotes.
Your SQL should look something like
select price, date from Price where Price_type = {0} order by date
Your method should look something like this:
private static DataTable GetData1( string query , string p0 )
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["bwic testConnectionString"].ConnectionString;
using ( SqlConnection con = new SqlConnection( constr ) )
using ( SqlCommand cmd = con.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter(cmd) )
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
SqlParameter p = new SqlParameter() ;
p.Value = p0Value ;
cmd.Parameters.Add( p ) ;
con.Open();
sda.Fill( dt );
con.Close();
}
return dt;
}
Don't forget to use brackets twice - in SELECT clause and in ORDER BY clause too.
in your code bolck as below
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
change it to
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
The problem here is that you havent opened any connection before filling.
You haven't opened a connection anywhere. You must open the connection before you can use it.
If your whole class code is really this, you are missing a closing } at the end of the file for the
public partial class Default2 : System.Web.UI.Page
{
declaration.

Categories

Resources