Update Each Exisiting Row of SQL Server Table Using Loop - c#

I'm trying to update a certain column for each row in my SQL Server table, using ASP.NET, C#.
When this code is executed, I want the OrderNo of the first row in the column to be = 1. From then on, I want the OrderNo to increment by 1 for the other existing rows in the table.
At the moment, I can update the OrderNo of one row, however I can't get a loop to properly read through all the rows & increment as I would like.
Here is the structure of my table
And below is my C#:
con.Open();
SqlCommand cmdUpdateOrderNo;
cmdUpdateOrderNo = new SqlCommand("UPDATE tblImages SET [OrderNo]=#O WHERE [OrderNo] = 2;", con);
cmdUpdateOrderNo.Parameters.AddWithValue("#O", 4);
cmdUpdateOrderNo.ExecuteNonQuery();
Here is the reason I need to update the OrderNo:
protected void Timer1_Tick(object sender, EventArgs e)
{
int i = (int)ViewState["ImageDisplayed"];
i = i + 1;
ViewState["ImageDisplayed"] = i;
DataRow imageDataRow = ((DataSet)ViewState["ImageData"]).Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == i.ToString());
if (imageDataRow != null)
{
Image1.ImageUrl = "~/MyImages/" + imageDataRow["name"].ToString();
lblImageName.Text = imageDataRow["name"].ToString();
lblImageOrder.Text = imageDataRow["order"].ToString();
lblImageDesc.Text = imageDataRow["Desc"].ToString();
}
else
{
SetImageUrl();
}
}
private void SetImageUrl()
{
DataSet ds = new DataSet();//Creating a dataset
SqlDataAdapter da = new SqlDataAdapter("SELECT Name, [Order], [Desc] FROM tblImages", con);
da.Fill(ds, "image");
ViewState["ImageData"] = ds;//storing the dataset in a ViewState variable
ViewState["ImageDisplayed"] = 1;//storing order number of the image currently displayed
DataRow imageDataRow = ds.Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == "1");
Image1.ImageUrl = "~/MyImages/" + imageDataRow["name"].ToString();
lblImageName.Text = imageDataRow["name"].ToString();
lblImageOrder.Text = imageDataRow["order"].ToString();
lblImageDesc.Text = imageDataRow["Desc"].ToString();
}

I agree with #Jamiec on this that it seems like a bad idea, but you don't need a loop if it's really what you want to do. Here's an example using a CTE and a Window Function.
Example
WITH T AS
( SELECT
*,
ROW_NUMBER() OVER (ORDER BY ID) as RN
FROM YourTable
)
/* this shows you the results of the CTE,
specifically the ROW_NUMBER()
which will replace the OrderNo in the code below */
SELECT * FROM T
Runing This WIll Update Your Table
WITH T AS
( SELECT
*,
ROW_NUMBER() OVER (ORDER BY ID) as RN
FROM YourTable
)
UPDATE T
SET OrderNo = RN

When dealing with SQL you almost never want to be writing loops.
Try changing your command to this
; with cte as
(
select *, row_number() over (order by ID) as rn
from tblImages
)
update tblImages
set OrderNo = rn
from cte

Related

MySQL trigger + insert

i'm trying to get my current id from a table pk to insert on another table fk, my next try is set a trigger inside database.
CREATE PROCEDURE `INSERIR CODIGO DISPENSACAO` ()
CREATE TRIGGER `productInsert`
BEFORE INSERT ON `produtos_disp`
FOR EACH ROW
BEGIN
set NEW.ID_PRODISP = (select max(ID)
from dispensacao p
);
END
what I want to set max id from dispensacao table which is going to be inserted from auto_increment on insert to it, on my fk codigo_disp for every row.
Managed to get max id using a combobox as descending order.
used
MySqlConnection connection = new MySqlConnection("connectionString");
string selectQuery = "select ID from dispensacao ORDER BY id DESC LIMIT 1";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbid.DisplayMember = "ID";
Cmbid.DataSource = dt2;
this return the max id from the table and all you need to do is make it invisible so user won't change as it is a combobox

Button to Load more data to DatagridView, more than 20000 register C#

I have a Big doudt.
I'm trying to load my data with this code:
SqlConnection con = new SqlConnection(Login.conectData);
con.Open();
DataSet dsFabricantes = new DataSet();
SqlDataAdapter daFabricantes = new SqlDataAdapter("SELECT TOP 100 * FROM
Fabricantes", con);
dsFabricantes.Clear();
//prencher a tabela
daFabricantes.Fill(dsFabricantes, "Fabricantes");
tabelaFabricantes.DataSource = dsFabricantes;
tabelaFabricantes.DataMember = "Fabricantes";
//para mudar o que está escrito no cabeçalho das colunas
tabelaFabricantes.Columns[1].HeaderCell.Value = "Nome do
Fabricante";
tabelaFabricantes.Columns[2].HeaderCell.Value = "Observações";
con.Close();
tabelaFabricantes.ClearSelection();
I Want to make a button to load more register in my datagridView. Onload of the app I am changing just 100 register. My question is:
How can I add a button to onClickbutton this button, my dataGrideView, Load more 100 Register and so on and so on ?
little Help
thank you
Bráulio José
You'll need to dynamically adapt your SqlDataAdapter() call.
First set some global variables on page/formOnLoad method
global int startRow = '1';
global int maxColRank = testMaxRows();
#set left button active = false
leftButton.Active = false;
To do this, class your DataGridViewLoader separately to accept no parameters. Name the class mySqlGridViewLoaderClass()
at the beginning of this class input these values:
string MaximumRows = '100';
string StartRowIndex = StartRow.ToString();
In the SQL connector for this DataGridViewLoader, use a query similar to
SELECT colRank, col1, col2
FROM
(SELECT col1, col2,
ROW_NUMBER() OVER(ORDER BY col2 DESC) AS colRank
FROM Fabricantes
) AS rowNumQuery
WHERE colRank > <i>StartRowIndex</i> AND
colRank <= (<i>StartRowIndex</i> + <i>MaximumRows</i>
)
Your class should perform DataGridView loading operation, then return a second scalar value for MAX(colRank).
#new connector
SqlDataAdapter daFabricantes = new SqlDataAdapter("SELECT Max(colRank) FROM
(SELECT max(colRank)
FROM
(SELECT col1, col2,
ROW_NUMBER() OVER(ORDER BY col2 DESC) AS colRank
FROM Fabricantes
) AS rowNumQuery
WHERE colRank > <i>StartRowIndex</i> AND
colRank <= (<i>StartRowIndex</i> + <i>MaximumRows</i>
))", con2);
int mr = (Int32) con2.ExecuteScalar();
return mr;
class a second SQL connector loader to test max Rows and return a scalar value. name the class testMaxRows()
In the sql connector, use a query similar to:
Select count(col1) DIST from fabricantes;
Return the count to the tr variable. The last 2 lines of maxRows class should be:
int tr = (Int32) con.ExecuteScalar();
return tr;
In your form designer, create a button for '<' and '>'
Set < button to inactive. > button to active
In the '<' ButtonOnClick() event:
rightButton.Active = true;
if (StartRow != '1')
{
StartRow -= 100;
# your class expects a return value, so we'll initialize one
int mr = (Int32) mySqlGridViewLoaderClass();
if (StartRow == 1)
{
leftButton.Active = false;
}
}
In the '>' ButtonOnClick() event:
leftButton.Active = true;
StartRow += 100;
int maxRank = (Int32) mySqlGridViewLoaderClass();
if ( maxRank >= maxColRank)
{
rightButton.Active = false;
}

get multiple string outputs from stored procedure using entity framework

The following stored procedure displays three strings and a table row result as output.
Is there any way we can display all the results on a mvc view output panel using entity framework?
I could see the first string result in the code below. But is there anyway to get the other two select string outputs and
the table row result.
private CustomerEntities db = new CustomerEntities();
public ActionResult Index()
{
var results = db.usp_CustomerData("124544", 1500);
var abc = results.ToList();
return View();
}
ALTER PROCEDURE [dbo].[usp_CustomerData]
#CustomerID varchar(6),
#MinsBack int
AS
BEGIN
DECLARE #Count int
SET #Count = (SELECT Count(*)
FROM Customer WITH (NOLOCK)
WHERE CustomerID = #CustomerID AND
DATEDIFF(mi, ReceivedAt, GETUTCDATE()) < #MinsBack)
IF (#Count = 1)
SELECT 'Ok: 1 message in Customer table'
ELSE
SELECT 'ERROR: Expected 1 message in Customer table, but found ' + CONVERT(varchar(3), #Count) + ' messages.'
SET #Count = (SELECT Count(*)
FROM CustomerDetails WITH (NOLOCK)
WHERE CustomerID = #CustomerID AND
DATEDIFF(mi, LastUpdatedAt, GETDATE()) < #MinsBack)
IF (#Count = 1)
SELECT 'Ok: 1 record in CustomerDetails table'
ELSE
SELECT 'ERROR: Expected 1 record in CustomerDetails table, but found ' + CONVERT(varchar(3), #Count) + ' records.'
SET #Count = (SELECT Count(*)
FROM CustomerProduct WITH (NOLOCK)
WHERE CustomerID = #CustomerID AND
DATEDIFF(mi, LastUpdatedAt, GETDATE()) < #MinsBack)
IF (#Count = 1)
SELECT 'Ok: 1 record in CustomerProduct table'
ELSE
SELECT 'ERROR: Expected 1 record in CustomerProduct table, but found ' + CONVERT(varchar(3), #Count) + ' records.'
SELECT *FROM Customer where customerID = #CustomerID
END
As suggestion you could create a temporary table in your SQL script which will be used as temporary store.
CREATE TABLE #Results
(
Message VARCHAR(512)
)
Instead of a direct SELECT in each IF or ELSE you should insert the string into the temp table.
At the end you could reach your goal to get all inserted strings to return them by:
SELECT * FROM #Results
To get customers - like you do at the end - you should trigger a new query to database.
Depending on your case you should consider to querying the database by data context instead of querying the database by store procedures.
You need to do something as suggest in this link but I summarized below
For each results set you will need to do a reader.NextResult();
var someReturnObject = new ResultObject();
using (var context = new LinqPadDbContext(#"Server=localhost\SQLEXPRESS;Database=StackOverflow;Trusted_Connection=True;"))
{
var cmd = context.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[GetSomeData]";
try
{
context.Database.Connection.Open();
var reader = cmd.ExecuteReader();
var result1 = ((IObjectContextAdapter)context).ObjectContext.Translate<string>(reader);
someResultObject.Text1 = result1.First();
//for each extra result, start here
reader.NextResult();
var users = ((IObjectContextAdapter)context).ObjectContext.Translate<User>(reader);
someResultObject.Users = users.Select(x => x);
//stop here
}
finally
{
context.Database.Connection.Close();
}
}

simplifying non-parametrized mysql queries

I have a problem with mySql query below
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
#curRank := #curRank + 1 AS rank
FROM hospitals h, ( SELECT #curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = #hospitalID
and city = #city
This query I am using to find the rank of particular item & it is working properly. But while runining in program I get Fatal errors of Parameter '#curRank' must be defined. But that is mysql syntax then how can I get it's parameters?
UPDATE
string str = "SELECT name, hospitalID, currentAvgRating, rank FROM (SELECT name,hospitalID,currentAvgRating,city,#curRank := #curRank + 1 AS rank FROM hospitals h, (SELECT #curRank := 0) r ORDER BY currentAvgRating DESC) toplist WHERE toplist.hospitalID = #hospitalID and city = #city";
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("#hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("#city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
You can get the rank for a particular hospital/city pair without a rank. Here is a close approximation to your query:
select count(*) + 1 as ranking
from hospitals h cross join
(select h.currentAvgRating
from hospitals h
where h.hospitalID = #hospitalID and h.city = #city
) hh
where h.currentAvgRating > hh.currentAvgRating;
Unlike your code, this gives all hospitals with the same rating, the same ranking.
If you don't want to change the code, then refer to this answer. Actually, I'll quote the relevant part:
I have to add
;Allow User Variables=True
to the connection string
Your SQL is correct I think there are conflect with C# command parameter and mySQL parameter
try this modification of SQL code like this
SELECT name, hospitalID, currentAvgRating, rank
FROM ( SELECT name,hospitalID,currentAvgRating,city,
#curRank := #curRank + 1 AS rank
FROM hospitals h, ( SELECT #curRank := 0) r
ORDER BY currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = ?hospitalID
and city = ?city
you c# like this
string str = <Example Above>;
con.Open();
MySqlCommand cmd = new MySqlCommand(str, con);
cmd.Parameters.AddWithValue("?hospitalID", generalID.Text);
cmd.Parameters.AddWithValue("?city", cityName.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
Just changeing the C# command parameter using ? than using #

input parameter to mysql syntax on C#

I try to input value but #numVal doest not work ( on the line begin with arr[10] )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection conDatabase = new MySqlConnection("Data Source=localhost;" +
"Persist Security Info=yes;" +
"UserId=tee; PWD=t5794849; database=ph3;");
conDatabase.Open();
// MySqlCommand cmdDatabase = new MySqlCommand("DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc;", conDatabase);
Console.WriteLine("Enter username");
string input = Console.ReadLine();
try
{
int numVal = Convert.ToInt16(input);
}
catch (FormatException )
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException )
{
Console.WriteLine("The number cannot fit in an Int32.");
}
string[] arr = new string[11];
arr[0] = "UPDATE `member` SET `amphurecode`= SUBSTRING(member.own,3,4)";
arr[1] = "UPDATE `member` SET `provincecode`= SUBSTRING(member.own,3,2)";
arr[2] = "DROP TABLE IF EXISTS `q_mem_tim`; create table q_mem_tim as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.novote, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE";
arr[3] = "DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc";
arr[4] = "DROP TABLE IF EXISTS `q_mem_hno` ; create table q_mem_hno as select member.Hno, member.Moo, member.tambol, COUNT( member.Hno ) AS cntHno, COUNT(DISTINCT member.Ssurname) as NoSur FROM member GROUP BY member.Hno, member.Moo, member.tambol ORDER BY cntHno DESC ";
arr[5] = "DROP TABLE IF EXISTS `q_pro_ori`; create table q_pro_ori as Select member.provincecode, count(*) As cnt From member Group By member.provincecode Order By cnt Desc ";
arr[6] = "DROP TABLE IF EXISTS `q_am_ori`; create table q_am_ori as Select member.amphurecode, member.provincecode, count(*) As cnt From member Group By member.amphurecode, member.provincecode Order By cnt Desc ";
arr[7] = "DROP TABLE IF EXISTS `Sur_Hno_`; create table Sur_Hno_ as SELECT count( * ) , Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol FROM q_mem_tim GROUP BY q_mem_tim.Ssurname, q_mem_tim.Hno, q_mem_tim.Moo, q_mem_tim.tambol ORDER BY count( * ) DESC";
arr[8] = "DROP TABLE IF EXISTS `q_dup_own`; create table q_dup_own as SELECT Count(*) as n ,member.own FROM member GROUP BY member.own order by n DESC ";
// arr[9] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, member.fathercode , member.mathercode, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d ,member.inputstaf FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE WHERE DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) < 30 and DAYOFYEAR(member.dateofbirth)-DAYOFYEAR(NOW()) > -1 order by DAYOFYEAR(member.dateofbirth)";
arr[9] = "ALTER TABLE `q_mem_tim` ADD `agec` VARCHAR( 10 ) NULL ";
// arr[10] = "UPDATE q_mem_birth SET agec = CASE WHEN y < 10 THEN 'ด' WHEN y > 10 and y < 20 and Sex='ญ' THEN 'วญ' WHEN y > 10 and y < 20 and Sex='ช' THEN 'วช' ELSE 'ผญ' END";
arr[10] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT q_mem_tim.idmember,q_mem_tim.own,q_mem_tim.PROVINCE_NAME,q_mem_tim.AMPHUR_NAME,q_mem_tim.novote,q_mem_tim.Sname,q_mem_tim.Ssurname,q_mem_tim.Hno,q_mem_tim.Moo,q_mem_tim.Sex,q_mem_tim.tambol,q_mem_tim.dateofbirth,q_mem_tim.migratedate,q_mem_tim.y,q_mem_tim.d,q_mem_tim.agec FROM q_mem_tim where q_mem_tim.dateofbirth is not null and q_mem_tim.dateofbirth != '00000000' and day(q_mem_tim.dateofbirth) != '00' and day(q_mem_tim.dateofbirth) > 0 and day(q_mem_tim.dateofbirth) < 11 and month(q_mem_tim.dateofbirth) != '00' and month(q_mem_tim.dateofbirth) = #numVal order by tambol,Moo, month(dateofbirth),day(dateofbirth) ";
foreach (string s in arr)
{
Console.WriteLine(s);
MySqlCommand cmdDbase = new MySqlCommand((s), conDatabase);
cmdDbase.CommandTimeout = 500;
cmdDbase.ExecuteNonQuery();
}
conDatabase.Close();
}
}
}
1)Truncate the tables; don't drop them and remake them because when you drop them you have to do the indexes and add the Primary Keys again.
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Truncate Table Table";
cm.CommandType = CommandType.Text;
cm.ExecuteNonQuery();
}
2)Don't forget the # symbol; it helps with anything SQL:
using(var cm = _dbConnection.CreateCommand())
{
cm.CommandText = #"Select *
From table
Where Id = #Id";
cm.CommandType = CommandType.Text;
cm.Parameter.AddWithValue("Id", id);
cm.ExecuteNonQuery();
}
I know you're not doing it this way and you're using a string array (just put a foreach loop outside the using statement and replace the cm.CommandText value with the string's value) but with the examples it should help you or at least give you some ideas.
You need to add a MySqlParameter to the command named numVal.

Categories

Resources