I have an UPDATE stored procedure that works good from SQL Server query:
GO
ALTER PROCEDURE [dbo].[UpdateMedicalCard]
#RecordingCode int,
#BeginTreatmentDate date,
#EndTreatmentDate date,
#MainDiagnosis nchar(100),
#AttendantDiagnosis nchar(100),
#TreatmentResult nchar(50)
AS
BEGIN
UPDATE MedicalCard
SET BeginTreatmentDate = #BeginTreatmentDate,
EndTreatmentDate = #EndTreatmentDate,
MainDiagnosis = #MainDiagnosis,
AttendantDiagnosis = #AttendantDiagnosis,
TreatmentResult = #TreatmentResult
WHERE RecordingCode = #RecordingCode
END
But when i call this procedure from Visual studio it does not update.
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"Data Source=.;Initial Catalog=Policlinic;Integrated Security=SSPI";
connection.Open();
SqlCommand myCommand = connection.CreateCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "UpdateMedicalCard";
myCommand.Parameters.Add("#RecordingCode", System.Data.SqlDbType.Int);
myCommand.Parameters["#RecordingCode"].Value = dataGridView1.CurrentRow.Cells[0].Value;
myCommand.Parameters.Add("#BeginTreatmentDate", System.Data.SqlDbType.Date);
myCommand.Parameters["#BeginTreatmentDate"].Value = dataGridView1.CurrentRow.Cells[3].Value;
myCommand.Parameters.Add("#EndTreatmentDate", System.Data.SqlDbType.Date);
myCommand.Parameters["#EndTreatmentDate"].Value = dataGridView1.CurrentRow.Cells[4].Value;
myCommand.Parameters.Add("#MainDiagnosis", System.Data.SqlDbType.NChar);
myCommand.Parameters["#MainDiagnosis"].Value = "qwe";
myCommand.Parameters.Add("#AttendantDiagnosis", System.Data.SqlDbType.NChar);
myCommand.Parameters["#AttendantDiagnosis"].Value = dataGridView1.CurrentRow.Cells[6].Value;
myCommand.Parameters.Add("#TreatmentResult", System.Data.SqlDbType.NChar);
myCommand.Parameters["#TreatmentResult"].Value = dataGridView1.CurrentRow.Cells[7].Value;
var dataAdapter = new SqlDataAdapter(myCommand);
var dataTable = new DataTable();
dataAdapter.Update(dataTable);
connection.Close();
I think i do smth wrong at the last 4 rows. Help please.
Your command isn't going to return any result rows, so you don't need to use a DataTable or DataAdapter. You just need to call connection.ExecuteNonQuery() instead.
You may also want to double check that the data (specifically the dates, as they can be tricky since the field may or may not also store a time component depending on how the table is defined, match an existing row.
Related
how do I put an int variable in sql?
int x = Convert.ToInt32(Session["id"]);
string MySQL = #"UPDATE users SET
email = '"+Request.Form["email"]+"', pname =
'"+Request.Form["pname"]+"', accountname=
'"+Request.Form["accountname"]+"', pid = '"+Request.Form["pid"]+"', age =
'"+Request.Form["age"]+"',passw = '"+Request.Form["passw"]+"' where
id='x';";
Please don't use concatenated values in your SQL command. You are exposing your application to SQL Injection Attacks. Read more here.
Use SqlParameters instead. It is the proper way to do and safer when you are running sql commands against your database from your application.
If a value is int covert it to integer:
command.Parameters.AddWithValue("#id", int.Parse(Request.Form["id"]));
Here is a example of how to use parameters.
string mySql = #"UPDATE users SET email = #email, pname = #pname, accountname = #accountname, pid = #pid, age = #age, passw = #passw where id = #id;";
string connectionString = "Server=localhost\\SQLEXPRESS;Database=[your database];User Id=sa;Password=[your password];";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(mySql, connection);
command.Parameters.AddWithValue("#email", Request.Form["email"]);
command.Parameters.AddWithValue("#pname", Request.Form["pname"]);
command.Parameters.AddWithValue("#accountname", Request.Form["accountname"]);
command.Parameters.AddWithValue("#pid", Request.Form["pid"]);
command.Parameters.AddWithValue("#age", int.Parse(Request.Form["age"]));
command.Parameters.AddWithValue("#passw", Request.Form["passw"]);
command.Parameters.AddWithValue("#id", int.Parse(Request.Form["id"]));
connection.Open();
command.ExecuteNonQuery();
}
More about SqlCommand here.
see i have stored procedure which contain two select statement , please tell me how can i get two result set from single stored procedure.
Here is code ---
create proc spReturnsDataFromTwoTable
As
Begin
select * from TableOne
select * from TableTwo
End
Here is a way you can access yours two tables using data adapter:
SqlConnection sqlConn = new SqlConnection("ConnectionString");
SqlCommand sqlCmd = new SqlCommand("procedureName", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlCmd);
DataSet ds = new DataSet();
sda.Fill(ds);
sqlconn.Close();
// Retrieving yours stored tables from a DataSet.
DataTable dt1 = ds.Tables[0];
DataTable dt2 = ds.Tables[1];
for (int i = 0; i < purchaseListView.Items.Count; i++)
Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
SqlCommand cmdFifo = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
cmdFifo.Connection = con.DataBaseConnection;
cmdFifo.CommandType = CommandType.StoredProcedure;
cmdFifo.CommandText = "insertInToMain";
This is my code and I want to know if the loop affects performance of my software and if this is the right way to call stored procedure in loop.
I have stored the procedure in a class and I want to call it from a form when the save button is clicked and insert 10 items in the database via same stored procedure.
Well, you are opening 10 connections, and it seems that you are not closing them, so you may run out of connections, but im guessing that's not the whole code, could you post the entire for ?
I would suggest you to create a table and insert the whole data into it by iterating through all the inputs ie., try to create a single stored procedure.
Running a for loop multpile times is inefficient and also the database will generate the result set number of times which will affect your performance as well due to network overhead.
You are creating a new connection object for every item which is highly inefficient.
Create one connection object and execute the stored procedure n times with the product details. Alternatively create a stored procedure to accept 10 items and insert the data at that level.
Move this outside the loop (You can access con and cmd inside the loop without creating a new instance:
Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
Inside your loop, you can add all the parameters to the cmd object.
cmd.Parameters.Add("#Item", SqlDbType.Int);
cmd.Parameters["#Item"].Value = purchaseListView.Items[i];
cmd.ExecuteNonQuery();
You should set up your connection and stored procedure before the loop and only update command parameter values and exec within the loop. Like this:
Connection con = new Connection();
SqlCommand cmd = new SqlCommand();
SqlCommand cmdFifo = new SqlCommand();
con.OpenConnection();
cmd.Connection = con.DataBaseConnection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "insertDetail";
cmd.Parameters.Add("#Item", SqlDbType.Int);
cmdFifo.Connection = con.DataBaseConnection;
cmdFifo.CommandType = CommandType.StoredProcedure;
cmdFifo.CommandText = "insertInToMain";
//now that your connections & commands are set up, you can reuse them within the loop
for (int i = 0; i < purchaseListView.Items.Count; i++)
{
//ToDo:assign any SP parameter values
cmd.Parameters["#Item"].Value = purchaseListView.Items[i];
// ...
//then exec within the loop
cmd.ExecuteNonQuery();
cmdFifo.ExecuteNonQuery();
}
I am using VB.net and Sql server 2005.
I have GridView in Application where I have my CPUserID. There can be thousands records in GridView with different CPUserIDs.
Now I have a button "Allocate Token". But before allocating the token I want to check in my Token Table that if that CPUserID has already exists in table it should not allow user to allocate token and will return some message for that user.
For Each curRow As GridViewRow In GridView1.Rows
Dim cpuserid As Label = CType(curRow.Cells(1).FindControl("lblCPUserID"), Label)
Next
The TOKEN table structure is given below:
TokenID, CPUserID, StatusID (All Integer)
Please Suggest! with some example code
Perform a query on the Token table to see if there already exists a row in that table for the given id:
SELECT COUNT(*) FROM Token WHERE CPUserID = 5
for instance.
In order to do that in VB.NET, you'll have to use the SqlConnection and SqlCommand classes.
Also, be sure to make use of parameterized queries.
In C#, the code would look more or less like this:
SqlConnection conn = new SqlConnection ("here comes the connectionstring to the db.");
conn.Open();
try
{
SqlCommand cmd = new SqlCommand ();
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) FROM Token WHERE CPUserId = :p_UserId";
cmd.Parameters.Add ("p_UserId", SqlDbType.Int32).Value = 5;
object result = cmd.ExecuteScalar();
if( Convert.ToInt32(result) > 0 )
{
MessageBox.Show ("Token already exists for user");
}
}
finally
{
conn.Close();
}
In order to improve performance, you will have to make sure that you create the correct indexes on the Token table.
An index on CPUserId would maybe help for this query.
First of all thanks to all of them who responded for this question.
I solved above issues with below solutions:
SQL Procedure:
I created one procedure in SQL server 2005
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[uspUpdateAllocateToken]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[uspUpdateAllocateToken]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspUpdateAllocateToken]
( #CPUserID INT)
AS
IF NOT EXISTS(SELECT TokenID FROM tblToken WHERE CPUserId=#CPUserID AND StatusID IN (41,47))
BEGIN
UPDATE tblToken
SET
CPUserID = #CPUserID,
StatusID=47
WHERE
tblToken.TOKENID = (SELECT TOP 1 TOKENID FROM TBLTOKEN WHERE CPUSERID IS NULL AND STATUSID = 40)
END
Further in my application on my Button Click. I write below code:
Protected Sub ibtnAllocateTokens_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ibtnAllocateTokens.Click
Try
Dim conString As String = WebConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString
Dim con As New SqlConnection(conString)
con.Open()
Dim cmd As SqlCommand
For Each gvRow As GridViewRow In GridView1.Rows
cmd = New SqlCommand("uspUpdateAllocateToken", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#CPUserID", SqlDbType.Int).Value = CType(gvRow.Cells(1).FindControl("lblCPUserID"), Label).Text
cmd.ExecuteScalar()
lblAllocateTokenMessage.Visible = True
Next
Catch ex As Exception
ErrorHandler.WriteError(ex.Message)
End Try
End Sub
Please have a look and let me know if there seems any problem in this implementation.
Cheers!
I've got a sql stored proc that is working fine in SSMS. When I try and execute through code and assign the return to a dataset I am getting zero rows back. I've used the immediate window to ensure that I am sending the correct params to the stored proc and that is all good.
What else would cause me to get zero rows assigned to the dataset. Here is my code.
Thanks,
Mike
EDIT: I'm not getting any exceptions from SQL..
Public Function GetTransReporting(ByVal transNumber As Long, ByVal customerID As Long) As DataCommon.transReporting
Dim myTransReporting As New transReporting
Dim da As SqlDataAdapter
Dim prm1 As SqlParameter
Dim prm2 As SqlParameter
mcmd = New SqlCommand
mcmd.CommandType = CommandType.StoredProcedure
mcmd.Connection = mcn
mcmd.CommandText = "GetTransReportingByCustomerID"
prm1 = New SqlParameter("#transNumber", Data.SqlDbType.BigInt)
prm1.Value = customerID
mcmd.Parameters.Add(prm1)
prm2 = New SqlParameter("#customerNumber", Data.SqlDbType.BigInt)
prm2.Value = transNumber
mcmd.Parameters.Add(prm2)
da = New SqlDataAdapter(mcmd)
da.Fill(myTransReporting)
Return myTransReporting
End Function
Got it.. if you take a look at my parameters up top I am accidentally assigning transaction to customer and customer to transaction. DOH!
Thanks,
Mike
Does your stored procedure start with SET NOCOUNT ON? The lack of this can sometimes cause issues if the stored procedure is processing multiple queries before the final SELECT.