Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Data is not being inserted into SQL Server using a stored procedure.
Insert code in ASP.NET / C#:
private void insert()
{
int regdno = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Insert_bmsstudent"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
string strFilename = uploadImage(photos);
cmd.Parameters.AddWithValue("#sphoto", strFilename.Trim());
cmd.Parameters.AddWithValue("#admyear", ddlyear1.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#addedddt", lbl_date.Text.Trim());
cmd.Parameters.AddWithValue("#admno", adm_no.Text.Trim());
cmd.Parameters.AddWithValue("#dateofadm", txt_dtadm.Text.Trim());
cmd.Parameters.AddWithValue("#sname", txt_sname.Text.Trim());
cmd.Parameters.AddWithValue("#preclass", ddlClass.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#presec", ddlsec.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#preroll", txt_roll.Text.Trim());
cmd.Parameters.AddWithValue("#priclass", txtpriclass.Text.Trim());
cmd.Parameters.AddWithValue("#prisec", ddlprisec.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#priroll", txt_priroll.Text.Trim());
cmd.Parameters.AddWithValue("#sgender", rdo_gender.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#sreligion", sreli.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#sdate", ddldate.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#smonth", dmonth.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#syear", ddlyear.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#caste", chk_caste.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#aadharno", txt_aadhar.Text.Trim());
cmd.Parameters.AddWithValue("#bg", txt_bg.Text.Trim());
cmd.Parameters.AddWithValue("#bplstatus", bpl_status.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#bplno", bpl_no.Text.Trim());
cmd.Parameters.AddWithValue("#svill", ddl_vill.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#spost", txt_postname.Text.Trim());
cmd.Parameters.AddWithValue("#sps", txt_ps.Text.Trim());
cmd.Parameters.AddWithValue("#sblock", txt_block.Text.Trim());
cmd.Parameters.AddWithValue("#sdist", txt_dist.Text.Trim());
cmd.Parameters.AddWithValue("#sstate", txt_state.Text.Trim());
cmd.Parameters.AddWithValue("#spincode", txt_pincode.Text.Trim());
cmd.Parameters.AddWithValue("#snationality", txt_nation.Text.Trim());
cmd.Parameters.AddWithValue("#fname", txt_fname.Text.Trim());
cmd.Parameters.AddWithValue("#fmob", txt_mobno.Text.Trim());
cmd.Parameters.AddWithValue("#foccu", txt_occu.Text.Trim());
cmd.Parameters.AddWithValue("#fqly", txt_qly.Text.Trim());
cmd.Parameters.AddWithValue("#faincome", txt_income.Text.Trim());
string strFilename2 = uploadImage2(photos2);
cmd.Parameters.AddWithValue("#fphoto", strFilename2.Trim());
cmd.Parameters.AddWithValue("#mname", txt_mother.Text.Trim());
cmd.Parameters.AddWithValue("#mmob", txt_mmobile.Text.Trim());
string strFilename3 = uploadImage3(photos3);
cmd.Parameters.AddWithValue("#mphoto", strFilename3.Trim());
cmd.Parameters.AddWithValue("#gname", txt_guar.Text.Trim());
cmd.Parameters.AddWithValue("#gmob", txt_gmob.Text.Trim());
cmd.Parameters.AddWithValue("#relative", rdorelative.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#relation1", ddl_relation1.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#rname1", txt_rname1.Text.Trim());
cmd.Parameters.AddWithValue("#rclass1", txt_rc1.Text.Trim());
cmd.Parameters.AddWithValue("#rsec1", txt_rsec1.Text.Trim());
cmd.Parameters.AddWithValue("#rroll1", txt_rroll1.Text.Trim());
cmd.Parameters.AddWithValue("#relation2", ddl_relation2.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#rname2", txt_rname2.Text.Trim());
cmd.Parameters.AddWithValue("#rclass2", txt_rc2.Text.Trim());
cmd.Parameters.AddWithValue("#rsec2", txt_rsec2.Text.Trim());
cmd.Parameters.AddWithValue("#rroll2", txt_rroll2.Text.Trim());
cmd.Parameters.AddWithValue("#relation3", ddl_relation3.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#rclass3", txt_rc3.Text.Trim());
cmd.Parameters.AddWithValue("#rsec3", txt_rsec3.Text.Trim());
cmd.Parameters.AddWithValue("#rroll3", txt_rroll3.Text.Trim());
cmd.Parameters.AddWithValue("#bankname", ddl_bank.SelectedValue.Trim());
cmd.Parameters.AddWithValue("#bbranch", txt_branch.Text.Trim());
cmd.Parameters.AddWithValue("#bifsc", txt_ifsc.Text.Trim());
cmd.Parameters.AddWithValue("#baccount", txt_baccount.Text.Trim());
cmd.Parameters.AddWithValue("#agree", declarationchk.Text.Trim());
cmd.Parameters.AddWithValue("#other1", other1.Text.Trim());
cmd.Parameters.AddWithValue("#other2", other2.Text.Trim());
cmd.Parameters.AddWithValue("#other3", other3.Text.Trim());
cmd.Parameters.AddWithValue("#other4", other4.Text.Trim());
cmd.Parameters.AddWithValue("#other5", other5.Text.Trim());
cmd.Parameters.AddWithValue("#other6", other6.Text.Trim());
cmd.Connection = con;
con.Open();
regdno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string message = string.Empty;
switch (regdno)
{
case -1:
message = "Student already exists.\\nEntered Students roll no. already been used. Please Enter a different roll no..";
break;
case -2:
message = "Supplied Account No. has already been used.";
break;
default:
message = "Registration successful. \\nYour Regd. no: " + regdno.ToString();
break;
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
lblmsg.Text = regdno.ToString();
string queryString = "http://example.org/admin/studentdetailspopup.aspx?userid=" + lblmsg.Text.Trim();
string newWin = "window.open('" + queryString + "');";
ClientScript.RegisterStartupScript(this.GetType(), "pop", newWin, true);
}
}
#endregion
Stored procedure :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Insert_bmsstudent]
#admyear NVARCHAR(50),
#addedddt DATE,
#admno NVARCHAR(50),
#dateofadm DATE,
#sname NVARCHAR(100),
#preclass NVARCHAR(50),
#presec NVARCHAR(50),
#preroll NVARCHAR(50),
#priclass NVARCHAR(50),
#prisec NVARCHAR(50),
#priroll NVARCHAR(50),
#sgender VARCHAR(50),
#sreligion VARCHAR(50),
#sdate NVARCHAR(50),
#smonth NVARCHAR(50),
#syear NVARCHAR(50),
#caste VARCHAR(50),
#sphoto NVARCHAR(50),
#aadharno NVARCHAR(50),
#bg NVARCHAR(50),
#bplstatus NVARCHAR(50),
#bplno NVARCHAR(50),
#svill VARCHAR(500),
#spost VARCHAR(50),
#sps VARCHAR(50),
#sblock VARCHAR(50),
#sdist VARCHAR(50),
#sstate VARCHAR(50),
#spincode VARCHAR(50),
#snationality VARCHAR(50),
#fname VARCHAR(250),
#fmob VARCHAR(50),
#foccu VARCHAR(50),
#fqly VARCHAR(50),
#faincome VARCHAR(50),
#fphoto VARCHAR(50),
#mname VARCHAR(50),
#mmob VARCHAR(50),
#mphoto VARCHAR(50),
#gname VARCHAR(50),
#gmob VARCHAR(50),
#relative VARCHAR(50),
#relation1 VARCHAR(50),
#rname1 VARCHAR(50),
#rclass1 VARCHAR(50),
#rsec1 VARCHAR(50),
#rroll1 VARCHAR(50),
#relation2 VARCHAR(50),
#rname2 VARCHAR(50),
#rclass2 VARCHAR(50),
#rsec2 VARCHAR(50),
#rroll2 VARCHAR(50),
#relation3 VARCHAR(50),
#rclass3 VARCHAR(50),
#rsec3 VARCHAR(50),
#rroll3 VARCHAR(50),
#bankname VARCHAR(500),
#bbranch NVARCHAR(500),
#bifsc NVARCHAR(50),
#baccount NVARCHAR(50),
#agree VARCHAR(50),
#other1 NVARCHAR(500),
#other2 NVARCHAR(500),
#other3 NVARCHAR(500),
#other4 NVARCHAR(500),
#other5 NVARCHAR(500),
#other6 NVARCHAR(500)
--#TaskParam int,
-- #Del int,
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT slno FROM fbmssms.bmsstudents WHERE preroll = #preroll)
BEGIN
SELECT -1 -- Username exists.
END
ELSE IF EXISTS(SELECT slno FROM fbmssms.bmsstudents WHERE baccount = #baccount)
BEGIN
SELECT -2 -- Email exists.
END
ELSE
BEGIN
INSERT INTO [fbmssms.bmsstudents]([admyear], [nvarchar], [addedddt], [admno], [dateofadm], [sname],
[preclass], [presec], [preroll], [priclass], [prisec], [priroll],
[sgender], [sreligion], [sdate], [smonth], [syear], [caste],
[sphoto], [aadharno], [bg], [bplstatus], [bplno], [svill],
[spost], [sps], [sblock], [sdist], [sstate], [spincode], [snationality],
[fname], [fmob], [foccu], [fqly], [faincome], [fphoto], [mname],
[mmob], [mphoto], [gname], [gmob], [relative], [relation1],
[rname1], [rclass1], [rsec1], [rroll1], [relation2], [rname2], [rclass2],
[rsec2], [rroll2], [relation3], [rclass3], [rsec3], [rroll3],
[bankname], [bbranch], [bifsc], [baccount], [agree],
[other1], [other2], [other3], [other4], [other5], [other6])
VALUES (#admyear, #addedddt, #admno, #dateofadm, #sname,
#preclass, #presec, #preroll, #priclass, #prisec, #priroll,
#sgender, #sreligion, #sdate, #smonth, #syear, #caste,
#sphoto, #aadharno, #bg, #bplstatus, #bplno, #svill,
#spost, #sps, #sblock, #sdist, #sstate, #spincode, #snationality,
#fname, #fmob, #foccu, #fqly, #faincome, #fphoto, #mname,
#mmob, #mphoto, #gname, #gmob, #relative, #relation1,
#rname1, #rclass1, #rsec1, #rroll1, #relation2, #rname2, #rclass2,
#rsec2, #rroll2, #relation3, #rclass3, #rsec3, #rroll3,
#bankname, #bbranch, #bifsc, #baccount, #agree,
#other1, #other2, #other3, #other4, #other5, #other6)
SELECT SCOPE_IDENTITY()
END
END
Error....................
Invalid object name 'fbmssms.bmsstudents'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'fbmssms.bmsstudents'.
Source Error:
Line 436: cmd.Connection = con;
Line 437: con.Open();
Line 438: regdno = Convert.ToInt32(cmd.ExecuteScalar());
Line 439: con.Close();
Line 440: }
Connection was there. Even my same coding is running in another page in same style. Here I don't know why it is not working.
INSERT INTO [fbmssms.bmsstudents] ... Invalid object name 'fbmssms.bmsstudents'.
There are a few possibilities here. As written, the INSERT statement is pointing to a table named [fbmssms.bmsstudents] in whatever database the connection object points to.
If you actually mean table bmsstudents in schema fbmssms, use [fbmssms].[bmsstudents].
If you mean table bmsstudents in the default schema in database fbmssms, use [fbmssms]..[bmsstudents] or [fbmssms].[dbo].[bmsstudents] (assumes that dbo is the default schema for the database).
If you mean the table named [fbmssms.bmsstudents], you are probably connected to an incorrect database. Add the database name and schema to the table name, e.g. [MyDatabase].[dbo].[fbmssms.bmsstudents].
Been trying to insert a date, along with some other string data, into SQL via C#, as such:
OperationResponse ICommon.addUser(userRequest request)
{
int? result = 0;
Guid countryGUID;
string requestParent = request.parent;
string requestName = request.name;
string requestSchool = request.school;
int requestGender = request.gender;
DateTime dateTimeDOB = DateTime.ParseExact(request.DOB, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
string requestEmail = request.email;
string requestMobile = request.mobile;
Guid.TryParse(request.countryID, out countryGUID);
string requestInstitution = request.institution;
try
{
result = s2u.AddUser(request.parent, request.name, request.school, request.gender, dateTimeDOB, request.email, request.mobile, countryGUID, request.institution);
}
catch (Exception ex)
{
if (isDebug() == true)
{
return new OperationResponse(ex.Message);
}
else
{
return new OperationResponse("Error: Database inaccessible.");
}
}
if (result == 1)
{
return new OperationResponse();
}
else
{
return new OperationResponse("Error: User could not be added.");
}
}
However whenever I try to run it in Fiddler it's been unsuccessful thus far, since the result always ends up being -1.
I suspect this may have something to do with the DOB not being inserted correctly, but I can't be sure. The request.DOB that I'm trying to parse is a string, the DOB column in the SQL table has the date datatype, and I'm trying to pass in dates in the format of "yyyy-MM-dd", but on the C# side I have to pass in the time too, being 12.00.00 AM by default. I don't know if this is causing problems. Any help is appreciated, and I'll provide further details if needed.
EDIT: The AddUser stored procedure is as such:
ALTER PROCEDURE [dbo].[AddUser]
-- Add the parameters for the stored procedure here
#parent nvarchar(300),
#name nvarchar(300),
#school nvarchar(500),
#gender int,
#DOB datetime2(7),
#email nvarchar(500),
#mobile nvarchar(20),
#countryID uniqueidentifier,
#institution nvarchar(500)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO [dbo].[Users] ([parent], [name], [school], [gender], [DOB], [email], [mobile], [countryID], [institution])
VALUES (#parent, #name, #school, #gender, #DOB, #email, #mobile, #countryID, #institution);
END
Check your string date time is in correct format or not. I believe it's not in correct format.
Moreover, why didn't you use the following method?
DateTime dt = Convert.ToDateTime(dateTime);
With EF, datetime is mostly handle as a datetime2 type, so it won't make much difference or cause any trouble.
In addition, write transaction handles in stored procedure with try & catch and try to find out if sp is giving any problems or not.
I have a procedure with a single select statement. I am need to create some 50 procedures like the one below..
create procedure foo1 as
select cityid, cityname from footballteam
the footballteam will be common in all my procedures, Instead of creating 50 single procedures, I want to code like below and send 3 parameters from my c# page
create procedure foo1 (#id bigint, #name varchar(50), #param bigint)as
select #id, #name from footballtem where #id =#param
can i pass like this in sql server ?/ How to do like this
will I am able to do procedure overloading in sql server, some time I need to pass only two parameters and i want to get a particular value , I will pass three or more parameters ....
For a pure TSQL answer:
create table footballtem(id int identity(1,1),cityid int, cityname varchar(50))
go
insert footballtem(cityid, cityname) values (123, 'abc')
insert footballtem(cityid, cityname) values (456, 'def')
go
create procedure foo1 (#id sysname, #name sysname, #param bigint) as
declare #sql nvarchar(100) = 'select ' + QUOTENAME(#id) + ','
+ QUOTENAME(#name) + ' from footballtem where '
+ QUOTENAME(#id) + '=#param'
exec sp_ExecuteSql #sql, N'#param bigint', #param
go
exec foo1 'cityid','cityname',123
(credit is due to Mikael Eriksson re QUOTENAME)
Note that QUOTENAME makes the #name and #id injection safe.
Note also, though, that the varying parameter (#param) is safe from injection - we don't need to validate that anywhere; and that this will allow query-plan re-use via sp_ExecuteSql
No; that would do a comparison on the parameter values, and return the parameter values. To do that, you would have to substitute the values at the caller, for example:
string idColumn = "id", nameColumn = "name";
string tsql = string.Format(#"
create procedure foo1 (#param bigint)
as select [{0}], [{1}] from footballtem where [{0}]=#param", idColumn,nameColumn);
and have 50 SPs; you can do the same in TSQL, using sp_ExecuteSQL against an already replaced string, but IMO it would be better to do this at the app tier than inside the database.
Also; question whether you really need stored procedures... that one isn't really going to help much; a parameterised TSQL query is much simpler, just as fast, and easier to deploy.
I'm not sure if I understand you correctly, but you can specify a default value for a stored procedure parameter in T-SQL. So you can omit it while calling.
CREATE PROCEDURE Proc1 #param1 int, #param2 int = -1 AS SELECT case when #param2=-1 then somefield else #param2 end as column from sometable where somekeyfield=#param1; GO
(assuming MS SQL Server)
MS SQL server does not support procedure overloading (as Oracle Does) but does support input and output parameters like this:
create procedure foo1 (
#param bigint
, #id bigint out
, #name varchar(50) out
)as
select
#id = fbt.id
,#name = fbt.name
from
footballteam fbt
where fbt.id =#param
#id and #name have to be passed in as null value output paramters of the correct type. After execution (cmd.executeNonQuery) you can inspect the command object to get the new parameter values back out.
I am not sure I am reading your question correctly, but if I am then this should get what you want..
*Adding better code sample after question *
//_assumes the following using statements at the top of code file:_
//using System.Data;
//using System.Data.SqlClient;
public string getTeam(int CityID)
{
string name;
using (var cmd = new SqlCommand("foo1",new SqlConnection("myConnectionStringGoesHere")))
{
cmd.Parameters.Add(new SqlParameter("#param", CityID));
cmd.Parameters.Add(new SqlParameter("#id", SqlDbType.BigInt){Direction=ParameterDirection.Output});
cmd.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar,50) { Direction = ParameterDirection.Output });
cmd.Connection.Open();
cmd.ExecuteNonQuery();
name = cmd.Parameters["#name"].Value.ToString();
cmd.Connection.Close();
}
return name;
}
I think you were asking for the following:
create procedure foo1 (#id bitint out, #name bigint out, #param bigint)
as
select #id=cityid, #name=cityname from footballteam where teamname = #param
But your question makes it seem like you are trying to dynamically change the column names per query.
There is a way to do overloading on MSSQL. Here how it goes:
For example we have a sp_Personel procedure which takes personel type as parameter and lists personel of that type.
CREATE PROCEDURE [dbo].[sp_Personel]
#PersonelType int
AS
SELECT Name, JoinDate, PersonelType, Salary
FROM Personel
WHERE PersonelType = #PersonelType
END
Now, you want another procedure which will be for personel join dates.
CREATE PROCEDURE [dbo].[sp_Personel];2
#JoinDate datetime
AS
SELECT Name, JoinDate, PersonelType, Salary
FROM Personel
WHERE JoinDate <= #JoinDate
END
To call second procedure from management studio;
[dbo].[sp_Personel];2 N'9/26/2010'