Adding new parameter to stored procedure - c#

I have a stored procedure in my database that currently takes in and utilizes 11 parameters (all working great). I need to add a new parameter to this for a new column I added.
We always explicitly define our columns in code, so there was no issue adding a column to the end of the table. However, if I add a new parameter in my stored procedure to populate this new column, will it throw an error back to my C# code if it isn't supplied, or will it default to null (or some other value) for the parameter?
Example C# code to call the stored procedure:
public static void InsertMailLog(string messageId, DateTime sentOrReceivedDate,
string fromAddress, string toAddress, string subject, string receivedMessage, string tailNumber,
string messageType, string direction, string sentOrReceived, string distributionList, ILogger AppEventLog, string filename = null)
{
List<string> lstParameterValues = new List<string>();
try
{
lstParameterValues.Add(messageId ?? "");
lstParameterValues.Add(sentOrReceivedDate.ToString("yyyy-MM-dd HH:mm:ss.fff"));
lstParameterValues.Add(fromAddress ?? "");
lstParameterValues.Add(toAddress);
lstParameterValues.Add(subject ?? "");
lstParameterValues.Add(receivedMessage ?? "");
lstParameterValues.Add(tailNumber ?? "");
lstParameterValues.Add(messageType ?? "");
lstParameterValues.Add(direction ?? "");
lstParameterValues.Add(sentOrReceived ?? "");
lstParameterValues.Add(distributionList ?? "");
lstParameterValues.Add(filename ?? ""); //THIS IS NEW, but it has not been published yet as the SP hasn't been updated.
CommonDAL.ExecSpNonQuery("spMailLogInsert", lstParameterValues);
}
catch (Exception ex)
{
CommonBLL.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, "Error", messageId, tailNumber, messageType, "", Settings.Default.ContentProvider, AppEventLog);
}
}
Example stored procedure code:
ALTER PROCEDURE [dbo].[spMailLogInsert]
#SdMessageId varchar(50),
#SentOrReceivedDate datetime,
#FromAddress varchar(100),
#ToAddress varchar(100),
#Subject varchar(255),
#Message varchar(MAX),
#TailNumber varchar(50),
#MessageType varchar(50),
#Direction varchar(50),
#SentOrReceived varchar(50),
#DistributionList varchar(50),
#Filename varchar(50) --THIS IS NEW
AS
SET NOCOUNT ON
INSERT MailLog (SdMessageId, SentOrReceivedDate, FromAddress, ToAddress,
[Subject], [Message], TailNumber, MessageType, Direction,
SentOrReceived, DistributionList, Filename --THIS IS NEW
)
VALUES (#SdMessageId, #SentOrReceivedDate, #FromAddress, #ToAddress,
#Subject, #Message, #TailNumber, #MessageType,
#Direction, #SentOrReceived, #DistributionList,
#Filename --THIS IS NEW
)
I completely understand that this is a terrible use of a stored procedure. I should be using Entity Framework, but it's already written, and I have a project to update the entire project to use EF in the DAL at a later date (this is very old code).
My question is, if I add the new parameter #Filename" to the stored procedure before the new C# code above gets published, will I get an error, or will the stored procedure parameter simply default to NULL? Or, if someone has a better way to default this to NULL or empty string, if it isn't supplied, I'm all ears.

Either Make it nullable like this.
ALTER PROCEDURE [dbo].[spMailLogInsert]
#SdMessageId varchar(50),
#SentOrReceivedDate datetime,
#FromAddress varchar(100),
#ToAddress varchar(100),
#Subject varchar(255),
#Message varchar(MAX),
#TailNumber varchar(50),
#MessageType varchar(50),
#Direction varchar(50),
#SentOrReceived varchar(50),
#DistributionList varchar(50),
#Filename varchar(50) = NULL --THIS IS NEW
......
Or Add a Default value like this:
ALTER PROCEDURE [dbo].[spMailLogInsert]
#SdMessageId varchar(50),
#SentOrReceivedDate datetime,
#FromAddress varchar(100),
#ToAddress varchar(100),
#Subject varchar(255),
#Message varchar(MAX),
#TailNumber varchar(50),
#MessageType varchar(50),
#Direction varchar(50),
#SentOrReceived varchar(50),
#DistributionList varchar(50),
#Filename varchar(50) = 'abc.txt' --THIS IS NEW
......

You could go ahead with the SP and just use a default parameter. https://technet.microsoft.com/en-US/library/ms189330(v=SQL.105).aspx
#Filename varchar(50) = NULL --THIS IS NEW

Based on your Stored Procedure it is considered required. To avoid it being required, you should add the following to your parameter:
#Filename varchar(50) = null
That will make it optional, which will allow you to avoid excessive Null checks in your code behind. Which can make your code turn to spaghetti quickly. This would be the easiest and least intrusive approach to solve your issue.

I completely understand that this is a terrible use of a stored procedure.
Er, no? It's a simple sproc, sure, but if all your SQL are sprocs, then this is the way to go.
I should be using Entity Framework [...]
Things in programming aren't always optimal, and you have to do what you have to do.
[...] if I add the new parameter "Filename" to the stored procedure before the new C# code above gets published, will I get an error, or will the SP simply default to NULL?
SQL will throw an error that the new parameter wasn't supplied through it's caller (ASP.Net). See here.
CREATE PROCEDURE Sales.uspGetSalesYTD
#SalesPerson nvarchar(50) = NULL -- NULL default value
AS

You should use a default value or it will get an error

Related

regdno = Convert.ToInt32(cmd.ExecuteScalar()); data not inserted [closed]

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].

C# stored procedure without passing optional parameters

My stored procedure in SQL Server looks like this:
ALTER PROC [dbo].[Rd_CreateModifyAssignmentType]
(
#AssignmentTypeId nvarchar(50),
#AssignmentTypeName nvarchar(50),
#mode int,
#Langtype nvarchar(10)=''
)
While calling it from C# like this:
SqlHelper.ExecuteNonQuery("Rd_CreateModifyAssignmentType", AssignmentTypeId, AssignmentTypeName, mode);
it throws an exception:
Parameter count does not match Parameter Value count.
I want to call the procedure in C# without passing optional parameters.
Please help me with this.
In your code you can write as:
if (Langtype.HasValue)
cmd.Parameters.AddWithValue("#Langtype", Langtype.Value);
So now what will happen is that your procedure will check for the value of optional parameter. If it will not find any value then the method is not going to add the #Langtype parameter into the command and it will use the default value as '' which you have specified in your database.
Please set default value by null all parameter in stored procedure:
ALTER PROC [dbo].[Rd_CreateModifyAssignmentType]
(
#AssignmentTypeId nvarchar(50) = null,
#AssignmentTypeName nvarchar(50) = null,
#mode int = null,
#Langtype nvarchar(10) = null
)

C# web service convert string to DateTime and insert into SQL

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.

EF6 stored procedure must declare scalar variable

I am trying to call a stored procedure using C# EF6 to bring back data. I have tried to run the stored procedure in SQL management studio and it seems to work fine, however when I try to run it in my application I get an error saying "Must declare the scalar variable "#devID"
Here is part of my method in my application calling the stored procedure
public IHttpActionResult GetMetrics(int deviceID, string attribute, string startDate)
{
if (deviceID == 0)
{
return NotFound();
}
var metrics = db.Database.SqlQuery<Metrics>("GetMetrics #devID, #MetricType, #startTime", deviceID, attribute, startDate).ToList();
and here is my stored procedure:
ALTER PROCEDURE [dbo].[GetMetrics]
-- Add the parameters for the stored procedure here
#devID int,
#MetricType nvarchar(20),
#startTime nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT *
FROM dbMetrics
WHERE deviceID = #devID and MetricType = #MetricType and timeStamp >= #startTime
ORDER BY timeStamp
END
As per the documentation, if you want to use named parameters, you need to pass SqlParameter objects like this:
var metrics = db.Database.SqlQuery<Metrics>("GetMetrics #devID, #MetricType, #startTime",
new SqlParameter("devID", deviceID),
new SqlParameter("MetricType", attribute),
new SqlParameter("startTime", startDate)
).ToList();

How to do Sql server procedure using parameters like where #para1 = #para2

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'

Categories