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.
Related
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();
}
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;
I want to Bind a checklistbox with Database in sqlserver2008. I am working in asp.net C# on a user control Module. I wrote a code. i want to know whether the code is perfact or not and also want to know that in which event i should place this code to get proper output.
{
int Post_Id = int.Parse(ViewState["ID"].ToString());
SqlConnection cn1 = new SqlConnection();
cn1.ConnectionString=
ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SelectTags", cn1);
DataTable ds = new DataTable();
SqlCommand cmnd1 = new SqlCommand("SelectTags", cn1);
cmnd1.Parameters.AddWithValue("#Post_Id",Post_Id);
cmnd1.CommandType = CommandType.StoredProcedure;
cn1.Open();
cmnd1.ExecuteNonQuery();
da.Fill(ds);
cn1.Close();
foreach (DataRow dr in ds.Rows)
{
String field1 = dr["Tag_Name"].ToString();
CheckBoxList2.Items.Add(field1);
CheckBoxList2.DataBind();
}
}
SQL query for sql server 2008
GO
/****** Object: StoredProcedure [dbo].[InsertPost2Tag] Script Date: 04/02/2013 09:47:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Alter PROCEDURE [dbo].[SelectTags]
-- Add the parameters for the stored procedure here
#Post_Id int
AS
BEGIN
SELECT mst_Tag.Tag_Name FROM mst_Tag INNER JOIN Post2Tag ON mst_Tag.tagId = Post2Tag.Tag_Id Where Post2Tag.Post_Id=#Post_Id
END
GO
Do this in page load witin
if(!ispostback){
CheckBoxList2.DataSource = ds; //This is the dataset that you fill from your stored procedure;
CheckBoxList2.DataTextField = "Tag_Name";
CheckBoxList2.DataValueField = "Tag_Name_Id";
CheckBoxList2.DataBind();
}
and take one more parameter Tag_Name_Id in your sp query..
SELECT mst_Tag.Tag_Name,Tag_Name_Id FROM mst_Tag INNER JOIN Post2Tag ON mst_Tag.tagId = Post2Tag.Tag_Id Where Post2Tag.Post_Id=#Post_Id
Remove this from your code
foreach (DataRow dr in ds.Rows)
{
String field1 = dr["Tag_Name"].ToString();
CheckBoxList2.Items.Add(field1);
CheckBoxList2.DataBind();
}
Hope this helps... If it is what you were asking for?
No need to do any thing Just choose data source for check list box and set the session variable with selected value of grid view in its selected index changed event.
It worked for me... and too easy to implement.
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.
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));