how to use parameter and stored procedure - asp.net

All what i am trying to do here is to set the Status field to "Complete" using stored procedure but for some reason it is not updating my table after i run the stored procedure. can someone please help me here and tell what am i doing wrong? thanks
//here is the stored proc
CREATE PROCEDURE sp_Update
#ID varchar
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if exists (select Post_ID from MyTable WHERE Post_ID = #ID)
BEGIN
UPDATE MyTable
SET Status = 'Complete'
WHERE Post_ID = #ID
END
END
//and here is the code behind
foreach (GridViewRow gr in GV_Action.Rows)
{
//string strID = gr.Cells[1].Text;
string ID = gr.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_Update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}

In the code "gr.Cells[1].Text" Cells[x] is zero based. If the ID is in the very first column then you need 'gr.Cells[0].Text'. Put a breakpoint on the very next line and see what value you have there.

Related

Sending multiple parameters from Asp.Net to my stored procedure in SQL Server

I have a list box in Asp.Net from where the user selects one or multiple parameters and send it to a stored procedure. The selected of number of parameters depends completely on the user so I don't know how many parameters the user is going to choose from the list box. I also want to retrieve data back from the table with those parameters when I click on the Submit button and display on a gridview. The issue I am having is I can send one parameter and retrieve data back from my stored procedure but I really don't know how to send multiple parameters from the list box to my stored procedure.
Below is the code for single parameter in Asp.Net
protected void Button_Click(object sender, EventArgs e)
{
string s = "Submit";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = lbCT.SelectedItem.Value;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvDS.DataSource = ds;
gvDS.DataBind();
con.Close();
}
Below is my stored procedure in SQL Server
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Submit]
#Name VARCHAR(12)
AS
BEGIN
SELECT *
FROM Employee
WHERE Name = #Name
END
You are sending just parameter and using equals "=" operator. Instead of this, you should send all selected items and split your parameter by delimiter.
Please follow these steps:
1.Create a new sql function for split name/names
CREATE FUNCTION dbo.splitstring (#stringToSplit VARCHAR(MAX))
RETURNS
#returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
2.Update your procedure
WHERE Name in (Select dbo.splitstring (#Names))
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Submit]
#Names VARCHAR(MAX)
AS
BEGIN
SELECT *
FROM Employee
WHERE Name in (Select dbo.splitstring (#Names))
END
3.Update your Codebehind parameter
cmd.Parameters.Add("#Names", SqlDbType.VarChar).Value = join all
selected items with ','
protected void Button_Click(object sender, EventArgs e)
{
string s = "Submit";
SqlCommand cmd = new SqlCommand(s, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Names", SqlDbType.VarChar).Value = /*join all selected items with ','*/
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvDS.DataSource = ds;
gvDS.DataBind();
con.Close();
}

a simple stored procedure to update table couldnt find parameter

I have a table and a stored procedure which updates a few column of table.Here is the stored procedure :
Create proc spReg
#UserId nvarchar(10),
#Experience nvarchar(5),
#Timings nvarchar(10),
#Notes nvarchar(max),
#PrefferedState nvarchar(20),
#PrefferedCity nvarchar(20),
#ResumePath varchar(256)
as
begin
Update tblRegCoachTrainers Set Experience=#Experience,Timings=#Timings,Notes=#Notes,PrefferedState=#PrefferedState,PrefferedCity=#PrefferedCity,ResumePath=#ResumePath where UserId=#UserId;
end
and the code-behind for the same :
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spReg", con);
cmd.Parameters.AddWithValue("#UserId", txtUserId.Text);
cmd.Parameters.AddWithValue("#Experience", ddlExperience.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Timings", ddlPartime.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Notes", txtNotes.Text);
cmd.Parameters.AddWithValue("#PrefferedState", ddlState.SelectedItem.Text);
cmd.Parameters.AddWithValue("#PrefferedCity", ddlCity.SelectedItem.Text);
cmd.Parameters.AddWithValue("#ResumePath", "/Attachments/" + hfResumePath.Value);
cmd.ExecuteNonQuery();
lblRegMessage.Text = "Your profile was created successfully.";
}
I debug the program by putting a break point and all necessary values are passed on to their respective parameters.It still throws an exception at
cmd.ExecuteNonQuery();
Error message :'spReg' expects parameter '#UserId', which was not supplied.
It would default to the Text command type, add:
cmd.CommandType = CommandType.StoredProcedure;

multiple SQL commands. Good style?

I got an asp.net application running perfectly fine. in my code i have the following lines
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con);
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con);
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
con.Open();
newGenreId = (int)getGenreId.ExecuteScalar();
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
i know database connections are valuable resources and i should be careful when using them. (open as late as possible and make sure they will be closed aswell)
My question now is this code considered bad style because im opening the connection then have as sql query to get an ID and then have another sql query to insert a record.
thanks you!
If you convert to using stored procedure, you can eliminate 1 round trip, therefore reducing network traffic and possibly increase performance.
using (SqlCommand cmd = new SqlCommand("Update_tblSong", con);
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#newGenre", newGenre);
cmd.Parameters.AddWithValue("#newTitle", newTitle);
cmd.Parameters.AddWithValue("#newArtistId", newArtistId);
cmd.Parameters.AddWithValue("#songId", songId);
cmd.ExecuteNonQuery();
}
Proc will be like this, I estimated on your variable size.
CREATE PROC Update_tblSong
(
#newGenre VARCHAR(25)
,#newTitle VARCHAR(50)
,#newArtistID INT
,#songID INT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #NewGenreID INT;
SELECT #NewGenreID = ID
FROM tblGenre
WHERE Genre = #newGenre;
UPDATE tblSong
SET Title = #newTitle
,ArtistId = #newArtistId
,GenreId = #NewGenreID
WHERE ( ID = #songId )
END;
Overall your code flow seems fine, you are using a single connection to execute multiple (related) commands.
You can improve it further with enclosing your command objects in using statement. Since they implement IDisposable interface, just like your connection object.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
using (SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con))
{
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
newGenreId = (int)getGenreId.ExecuteScalar();
}
using (SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con))
{
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
}
Why not use a single query with a subquery for your SQL?
UPDATE tblSong SET Title = #newTitle, ArtistId = #newArtistId, GenreId = (Select top 1 ID from tblGenre WHERE Genre=#newGenre ORDER BY Genre) WHERE (ID = #songId);

Inserting into sql database using the function

I am new in programming, especially in using sql server . I have a User page with text boxes and submit button. When a user enters information to text boxes and press the button, the information is added to database. There is a column UserID in the database which should be created after all information is added to the database.UserID should be consist of UserLastName and AutoIncrementNumber(column of the database which automatically is assigned to a new row) I have a function for this UserID column and i don't know how to make everything work. Please help me.
Thank you!
Here is code:
using (SqlConnection conn = new SqlConnection(#"Data Source=MyDataBase;Initial Catalog=MyDataBase;Integrated Security=True;"))
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial] SELECT [dbo].[usernamehandle](#UserFirstName),#UserLastName, #UserFirstName, #UserMiddleInitial", conn);
conn.Open();
CmdSql.Parameters.AddWithValue("#UserLastName", txtNewUserLN.Text.ToString());
CmdSql.Parameters.AddWithValue("#UserFirstName", txtNewUserFN.Text.ToString());
CmdSql.Parameters.AddWithValue("#UserMiddleInitial", txtNewUserMI.Text.ToString());
CmdSql.Connection = conn;
CmdSql.ExecuteNonQuery();
conn.Close();
And here is function:
USE [MyDataBase]
GO
/****** Object: UserDefinedFunction [dbo].[usernamehandle] Script Date: 04/07/2013 17:25:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[usernamehandle]
(#newuserName nchar(10))returns nchar(10)
AS
BEGIN
DECLARE #s2 nchar(256)
SET #s2 = ''
DECLARE #p int
DECLARE #ULN char(256)
DECLARE #UNAI int
SELECT #ULN = UserLastName FROM tblUser
SELECT #UNAI = UserNameAutoIncre FROM tbluser
SET #s2 = #UNAI
while #p <=6 begin
DECLARE #c int
SET #c = ascii(substring(#newUserName, #p, 1))
SET #s2 += char(#c)
end
return #s2
end
Try to call directly your function in SQL:
Notes: please check the parameter for the function. I am assuming the parameter is user's first name.
SqlCommand CmdSql = new SqlCommand
("INSERT INTO [tbluser] ([UserID],[UserLastName], [UserFirstName], [UserMiddleInitial]) SELECT [dbo].[usernamehandle](#UserFirstName), #UserLastName, #UserFirstName, #UserMiddleInitial, conn);
You can't use function to insert data, function only used for select statement means only for DDL not for DML, for that you have to use Stored Procedure.

SQL retrieving OUTPUT into a asp.net form

I have a SQL stored procedure that OUTPUTs the number to a row after I insert of few records. The query works great and returns what I need, although. I would like to take the output from the query and read it into a label. Can someone shine a little light? Thanks.
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#spName", txt_Name.Text));
cmd.Parameters.Add(new SqlParameter("#spSource", txt_Source.Text));
cmd.Parameters.Add(new SqlParameter("#spDateCreated", txt_DateCreated.Text));
paramReturnNumber = cmd.Parameters.AddWithValue("#out", SqlDbType.NVarChar);
paramReturnNumber.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
The Query:
ALTER PROCEDURE [dbo].[usps_InsertIntoMedia]
#spName varchar(100),
#spSource varchar(100),
#spDateCreated datetime
AS
SET NOCOUNT ON;
DECLARE #out nvarchar
BEGIN
INSERT INTO Media (Name, Source, DateCreated)
OUTPUT inserted.Number
VALUES(#spName,#spSource,#spDateCreated )
Select #out = Media.Number
FROM Media
END
I am using the following technique:
Hashtable ht = new Hashtable();
foreach (SqlParameter sqlp in cmd.Parameters)
{
if ((sqlp.Direction == ParameterDirection.InputOutput) ||
(sqlp.Direction == ParameterDirection.Output))
{
ht.Add(sqlp.ParameterName, sqlp.Value);
}
}
<lblName>.Text = (string)ht["#out"];
The solution to this problem was to specify the OUTPUT parameter using the SET statment.

Resources