a simple stored procedure to update table couldnt find parameter - asp.net

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;

Related

Implicit conversion from data type nvarchar to varbinary is not allowed. Use the CONVERT function to run this query

I have following code for button click.
status is bit
registerName is nvarchar
I dont know what the problem is.
SqlConnection conn = new SqlConnection(MiniMartSystem.dbConnection.dbConn_local);//(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString);
SqlCommand register = new SqlCommand("Insert Into Register (firstName,lastName,userName,Password,emailAddress,mobileNo,Department,dateofRegister,Status,registerName) VALUES (#firstName,#lastName,#userName,#Password,#emailAddress,#mobileNo,#Department,#dateofRegister,#Status,#registerName)", conn);
register.CommandType = CommandType.Text;
register.Parameters.AddWithValue("#firstName", tb_firstname.Text);
register.Parameters.AddWithValue("#lastName", tb_lastname.Text);
register.Parameters.AddWithValue("#userName", tb_loginname.Text);
register.Parameters.AddWithValue("#Password", tb_passowrd.Text);
register.Parameters.AddWithValue("#emailAddress", tb_emailaddress.Text);
register.Parameters.AddWithValue("#mobileNo", tb_mobiletno.Text);
register.Parameters.AddWithValue("#Department", dd_department.Text);
register.Parameters.AddWithValue("#dateofRegister", DateTime.Now.ToString("MM/dd/yyyy"));
register.Parameters.AddWithValue("#Status", "True");
register.Parameters.AddWithValue("#registerName", MiniMartSystem.dbConnection.username);
conn.Open();

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.

how to use parameter and stored procedure

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.

oraclehelper filldataset or another way to get SYS_REFCURSOR values at ASP.NET

To whom it may respond to,
We are developing our project using .net framework 4.0,Oracle 11gR2. The problem is that , we have to use Oraclehelper class, no other options, and we can't get SYS_REFCURSOR values . When googled ,
we have catched some pages writing about filldataset method of oraclehelper class, but this class doesn't exist in our Oraclehelper class.
Any workarounds, templates, examples etc. to get SYS_REFCURSOR values via Oraclehelper class?
Thank you for your concern,
Best Regards,
Kayhan YÜKSEL
assuming you are using the sourceforge.net/projects/oraclehelpernet "oraclehelper" it is build ontop of ODP (ie Oracle.DataAccess.Client)
all you would need to do is:
(this is from http://download.oracle.com/docs/cd/B28359_01/win.111/b28375/featRefCursor.htm)
String cmdTxt1 = "begin open :1 for select col1 from test; end;";
OracleCommand cmd = new OracleCommand(cmdTxt1, conn);
OracleParameter outRefPrm = cmd.Parameters.Add("outRefPrm",
OracleDbType.RefCursor, DBNull.Value, ParameterDirection.Output);
cmd.ExecuteNonQuery(); // Execute the anonymous PL/SQL block
You can also look in %oracle_home%\client_1\odp.net\samples\4\RefCursor for 7 examples (this is when ODP is installed that is)
Since the OracleHelper just creates a wrapper around ODP, all you need to do is create the parameter as OracleDbType.RefCursor and pass it into the call (be it an execute non-query or datareader or whatnot)
now to do this via a procedure:
PROCEDURE Get1CurOut(p_cursor1 out refCursor) is
BEGIN
OPEN p_cursor1 for select * from emp;
END Get1CurOut;
and to the C#
OracleCommand cmd = new OracleCommand("Get1CurOut", con);
cmd.CommandType = CommandType.StoredProcedure;
// Bind
OracleParameter oparam = cmd.Parameters.Add("refcursor", OracleDbType.RefCursor);
oparam.Direction = ParameterDirection.Output;
try
{
// Execute command; Have the parameters populated
cmd.ExecuteNonQuery();
// Create the OracleDataAdapter
OracleDataAdapter da = new OracleDataAdapter(cmd);
// Populate a DataSet with refcursor1.
DataSet ds = new DataSet();
da.Fill(ds, "refcursor1", (OracleRefCursor)(cmd.Parameters["refcursor1"].Value));
// Print out the field count the REF Cursor
Console.WriteLine("Field count: " + ds.Tables["refcursor1"].Columns.Count);
}
this is lifted (with slight modification) from %oracle_home%\client_1\odp.net\samples\4\RefCursor\sample1.cs
here is an (untested) OracleHelper example:
string connectionString = "User Id=scott;Password=tiger;Data Source=oracle";
CommandType commandType = CommandType.StoredProcedure;
string commandText = "Get1CurOut";
OracleParameter oparam = cmd.Parameters.Add("refcursor", OracleDbType.RefCursor);
oparam.Direction = ParameterDirection.Output;
OracleDataReader reader;
reader = OracleHelper.ExecuteReader(connectionString, commandType, commandText, oparam) ;
// show the first row
reader.Read();
// Print out SCOTT.EMP EMPNO column
Console.WriteLine("EMPNO: {0}", reader.GetDecimal(0));
// Print out SCOTT.EMP ENAME column
Console.WriteLine("ENAME: {0}", reader.GetString(1));

Resources