Exception when calling a stored procedure - c#

I have a SQL Server 2008 database and want to access a table from a C#-WCF via a stored procedure. The proc is a simple SELECT query that gets the row of a given id and fills the result into some outputparameters:
PROCEDURE [dbo].[get_stammInfo]
-- Add the parameters for the stored procedure here
#id int,
#strassenSchluessel int OUTPUT,
#hausNummer int OUTPUT,
#zusatz nvarchar(1) OUTPUT,
...
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 #strassenSchluessel = strassenSchluessel,
#hausNummer = hausNummer,
#zusatz = zusatz,
...
FROM gebaeudeStamm
WHERE id = #id
END
In my C#-Code, I create a commandobject, connect with the database and add the parameters to the commandobject.
When I call the ExecuteNonQuery, it throws the following exception
{"Die Prozedur oder Funktion 'getstammInfo' erwartet den '#id'-Parameter, der nicht bereitgestellt wurde."} which translate to something like "The procedure or function 'getstammInfo' expects the '
#id'-Parameter, which isn't provided"
Problem sounds clear, but actually I provided the id parameter. I can query it in the directwindow of VS2008:
_command.Parameters[0]
{#id}
base {System.Data.Common.DbParameter}: {#id}
CompareInfo: None
DbType: Int32
Direction: Input
IsNullable: false
LocaleId: 0
Offset: 0
ParameterName: "#id"
Precision: 0
Scale: 0
Size: 0
SourceColumn: ""
SourceColumnNullMapping: false
SourceVersion: Current
SqlDbType: Int
SqlValue: {7112}
TypeName: ""
UdtTypeName: ""
Value: 7112
XmlSchemaCollectionDatabase: ""
XmlSchemaCollectionName: ""
XmlSchemaCollectionOwningSchema: ""
As you can see, the id Parameter exists in the Parameterscollection and it has the same type like the parameter, the stored proc expects. I have no idea, what might be wrong, but it seems that the errormessage is wrong and some other error occured ...
Can anyone here hint me at what I should look to find the error?

Please show the code that you're using to call the procedure.
Your problem is that you put an # sign in the parameter name. When you add parameters to a SqlCommand, do not incldue the # sign.

Related

Same results are getting updated in all rows by using where clause in SQL Server

I'm running a stored procedure inside a foreach loop in c#. After completion, all the rows of a column are getting updated with the top most value. Below is the stored procedure:
ALTER PROCEDURE [dbo].[getservername8]
#number varchar(255)
AS
DECLARE #server_name varchar(500)
SELECT #server_name = short_description
FROM [Event_alerts].[dbo].[event_alerts]
DECLARE #s AS varchar(50)
SELECT #s = SUBSTRING(#server_name, CHARINDEX('-', #server_name) + 15, 50)
UPDATE event_alerts
SET server_name = #s
WHERE number = #number
This is the C# code:
using (SqlCommand command2 = new SqlCommand("getservername8", conn))
{
command2.CommandType = CommandType.StoredProcedure;
command2.Parameters.AddWithValue("#number",number);
command2.Parameters["#number"].Direction = ParameterDirection.Input;
command2.ExecuteNonQuery();
}
Any help would be much appreciated
The culprit is because you are getting the same value of #server_name for each call. So #s si also same for all. that is why you are inserting the same value in the column
select #server_name = short_description from [Event_alerts].[dbo].[event_alerts]
declare #s as varchar(50)
select #s= SUBSTRING(#server_name, CHARINDEX('-', #server_name) + 15, 50)
Your code has a valid where clause, so it should only be updating the matching rows. I can only speculate that all rows have the same value for number.
However, you seem to have an error in the definition of #server_name -- and that might be the problem you are referring to. There is no where clause so it is set to an arbitrary value -- possibly from what you would call "the last row". Although that nomenclature is a misinterpretation of what happens.
Your SP is too complex anyway. I suspect that you intend:
alter procedure [dbo].[getservername8] (
#number varchar(255)
) as
begin
update ea
set server_name = substring(short_description, charindex('-', short_description) + 15, 50)
from event_alerts ea
where number = #number;
end; -- getservername8
Also note the good programming practices:
The statements end in a semicolon.
The body of the SP uses begin/end.
The end is tagged with the name of the SP.

MySQL Stored Proc and c# data reader column wrong values

I have a situation in such a way that variable value has to be returned based on multiple condition. Initially it is set to passed parameter value. Below is just an algo,
create proc checkFlag (ppleid int, pflag bit, loginid int)
begin
declare vflag bit;
declare vhasRights bit;
declare vIsLocked bit;
declare vlockedUid int;
set vflag=pflag; // assign as passed param
if (vflag = 0)
then
select id, name,vflag as 'IsEditable'
from peopletable
where id=ppleid;
else
-- algo to check whether loginid has rights to edit
if (vhasrights = 1)
then
-- sql statements to check whether record is not write locked into vIsAlreadyLocked
if (vIsAlreadyLocked = 1)
then
--- sql statements to check whether locked user is login user in vlockedUid
if (vlockedUid = ploginid)
then
set vflag =1;
else
set vflag=0;
end if;
else
set vflag=0;
end if;
select id, name,vflag as 'IsEditable'
from peopletable
where id=ppleid;
end if;
end;
A. Sp. call withing sqleditor
call checkflag(values.....); returns appropriate value
B. Sp. call from c#
internal void ReadPpl()
{
bool initFlag=<flag based on client end condition>;
. code for creating connection and command of type storedproc
.
MysqlParameter prm=new parameter("pflag", initFlag);
.
.
. cmd.parameter(prm)
using (mysqldatareader rdr=cmd.ExecuteReader())
{
if (rdr.HasRows())
{
rdr.Read();
**bool IsWritable=Convert.ToBoolean(Convert.ToInt32(rdr["IsEditable"])); // This is the line that returns value as passed parameter but not based on conditions in db and params **
}
Any help will be appreciated.
Thanks in advance.
Got problem solved.
call proc(#flag...)
resulted #flag other than 0. So the else condition was executed.
But
MySqlParameter prm=new(....,Value=initValue);
considered intiValue as 0 hence, the only the first if condition in stored proc. was executed every time.

Stored procedure has too many parameters when being called [duplicate]

This question already has answers here:
"Procedure or function has too many arguments specified" But It Doesn't
(3 answers)
Closed 8 years ago.
I have a stored procedure with parameters:
ALTER PROCEDURE [dbo].[prAddSortament]
#Name varchar(255),
#ProcessingId varchar(35),
#ShapeId varchar(35),
#GostId varchar(35),
#PartOfId varchar(35),
#DescrArr varchar(max),--varbinary,
#tsVal varchar(max),
#SM varchar(max)
AS
BEGIN
And I'm calling it from my program that way:
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.MiSConStr))
{
SqlCommand cmd = new SqlCommand("dbo.prAddSortament", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", sort.Name);
cmd.Parameters.AddWithValue("#ProcessingId", sort.Processing.ObjectId);
cmd.Parameters.AddWithValue("#ShapeId", sort.Shap.ObjectId);
cmd.Parameters.AddWithValue("#GostId", sort.Gost);
cmd.Parameters.AddWithValue("#PartOfId", sort.PartOf);
cmd.Parameters.AddWithValue("#DescrArr", sort.Description);
cmd.Parameters.AddWithValue("#tsVal", ts);
cmd.Parameters.AddWithValue("#SM", sortMat);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
On cmd.ExeccutrNonQuery(); I have an exception
Procedure or function prAddSortament has too many arguments specified.
Can anybody help me?
If the number of parameters are same then try to check their types. It looks like there is some mismatch of the data types of the parameters.
Add below code it will specify the stored procedure you want to add :-
cmd.CommandText = "prAddSortament";
Extra info for this kind of error as detailed here http://www.sql-server-helper.com/error-messages/msg-8144.aspx :-
SQL Server Error Messages - Msg 8144
Error Message: Server: Msg 8144, Level 16, State 2, Procedure Stored
Procedure or Function Name, Line 0 Procedure or function Stored
Procedure or Function Name has too many arguments specified.
Causes:
As the message describes, this error is encountered when you are
passing arguments or parameters to a function or stored procedure
which is more than what the function or stored procedure is expecting.
To illustrate, let’s say you have the following function definition:
> CREATE FUNCTION [dbo].[ufn_Concat] ( #pString1 VARCHAR(10), #pString2
> VARCHAR(10) ) RETURNS VARCHAR(20) AS BEGIN
> RETURN ISNULL(#pString1 + ' ', '') + ISNULL(#pString2, '') END
This function expects only 2 arguments, namely #pString1 and
> #pString2. To use this function, you do the following: SELECT
> [dbo].[ufn_Concat] ( [FirstName], [LastName] ) AS [FullName] FROM
> [dbo].[Customers]
The error will be encountered you pass more than 2 arguments or
> parameters to the function, as follows: SELECT [dbo].[ufn_Concat] (
> [FirstName], [MiddleName], [LastName] ) AS [FullName] FROM
> [dbo].[Customers]
>
Server: Msg 8144, Level 16, State 2, Line 1 Procedure or function
dbo.ufn_Concat has too many arguments specified.
Solution/Workaround:
To avoid this error from happening, always make sure that you pass the
same number of arguments that a stored procedure or function is
expecting. To know the parameters expected by a stored procedure, you
can use the sp_help system stored procedure and pass the name of the
stored procedure as the parameter.
That was my great fault. I'm using two versions of database, and in the connection string was specified old version of DB, where dbo.prAddSortament exists but have less parameters.

Parameter does not exist as a stored procedure parameter

ALTER PROCEDURE [dbo].[SelectCompletionNonCompletionCourseReport]
#LearnerName NVARCHAR(510) = NULL,
#ManagerId INT = NULL,
#CourseId INT = NULL,
#StartDateFrom SMALLDATETIME = NULL,
#StartDateTo SMALLDATETIME = NULL,
#TeamList XML = NULL,
#JobID NVARCHAR(max)=NULL,
#CourseStatus NVARCHAR(20)=NULL,
#ReportAdminID INT=0,
#ReportTeamList NVARCHAR(max)=NULL,
#RowsTotal int = 0,
#PageIndex int = 1,
#RowsPerPage int = 10
AS
BEGIN
DECLARE #TblCrieiria TABLE
(
id INT IDENTITY(1, 1),
areacode NVARCHAR(11),
regioncode NVARCHAR(11),
teamcode NVARCHAR(11)
)
IF #TeamList IS NULL
BEGIN
INSERT INTO #TblCrieiria VALUES(NULL,NULL,NULL)
END
BEGIN
This is the beginning of the procedure...
using (Database db = new Database(DScape.DAL.Config.ConfignPropertyName.DSCAPELMS_CONNECTION_STRING_NAME))
{
var cmd = new SqlCommand
{
CommandText = "SelectCompletionNonCompletionCourseReport",
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#LearnerName", LearnerName);
cmd.Parameters.AddWithValue("#ManagerId", ManagerId);
cmd.Parameters.AddWithValue("#CourseId", CourseId);
cmd.Parameters.AddWithValue("#StartDateFrom", StartDateFrom);
cmd.Parameters.AddWithValue("#StartDateTo", StartDateTo);
cmd.Parameters.AddWithValue("#TeamList", TeamList);
cmd.Parameters.AddWithValue("#JobID", JobID);
cmd.Parameters.AddWithValue("#CourseStatus", CourseStatus);
cmd.Parameters.AddWithValue("#ReportAdminID", ReportAdminID);
cmd.Parameters.AddWithValue("#ReportTeamList", ReportTeamList);
cmd.Parameters.AddWithValue("#PageIndex", 1);
DataSet dsClient = db.GetDataSet(cmd);
if (dsClient.Tables.Count > 0)
return dsClient.Tables[0];
else
return null;
}
This is the method which communicates with the procedure, and it gaves me an error
Parameter does not exist as a stored procedure parameter/ function/procedure take too many arguments...
It's about #PageIndex parameter. Doesn't matter what is the value, we don't talk for values here but for parameter which is defined in the stored procedure but doesn't work?
And for the record, this problem did pop-up today w/o any code writing/modifying just appeared as I tried to do that report, when yesterday it was all good...I have a teammate which is next to me with absolute the same code both in sql and c# and it works just fine on his pc, but mine throws this errors, I'm trying to resolve this from 3 hours and I am completely out of answers , so please give me direction in which should I continue to resolve this .....................
and I say again, the problem is not from the connection to DB or type of the parameter or the value, the error is committed with the parameter itself - does not exist in the procedure, which is insane in my opinion.
Given that all parameters are optional, you are not required to explicitly provide any of them from your client code. Default values will be provided for you by SQL Server. The contract explictly states it in the stored procedure's signature.
An optional parameter is exactly that: optional. If you had provided the incorrect number of parameters, SQL Server would have returned a different error, indicating that the number of parameters was incorrect. This is not the case. Instead, you are seeing that you are asking for a parameter that is undefined, which indicates that the stored procedure signature you think you are calling does not match the stored procedure signature you are actually calling.
Verify that you are both connecting to the same database instance. If you are not, verify that the stored procedure is identical on both database instances.
parameter count doesnt match. check the params again.
You have to send parameters for rowstotal and rowsperpage as well because you have declared them at the top before "begin" clause.
If you do not want to send that params and they will be just constant, please declare them below as variable or constant, not a parameter.
i.e.
CREATE PROCEDURE DeleteById
#TableName sysname,
#Id int
AS
BEGIN
DECLARE #StrId AS VARCHAR(50)
SET #StrId = CONVERT(VARCHAR(50), #Id)
--any sp code here
END
Hope this helps.

Out of range error from C# to SQL

I have a stored procedure as follows
create procedure [dbo].[PriceConfirm]
#quote float,
#membershipType int,
#promocode nvarchar(20),
#giftCertificateCode nvarchar(20)
as
if(LEN(#giftCertificateCode)>1)
begin
declare #giftType int
select #giftType = MembershipType from GiftCertificate where GiftCertificateCode=#giftCertificateCode
if #giftType = #membershipType
begin
select 1 as result
end
else
begin
select 0 as result
end
end
else
begin
declare #total float
select #total = Price from MembershipType where TypeID=#membershipType
declare #discount float
select #discount = 0
if(LEN(#promocode)>1)
begin
select #discount = DiscountAmount from Membership_Promo where Promocode=#promocode and MembershipType = #membershipType
end
else
begin
select #discount=0
end
if ABS(#total-#discount-#quote) <.01
begin
select 1 as result
end
else
begin
select 0 as result
end
end
And if I just execute the stored procedure in SQL Server Management Studio, it works.
exec PriceConfirm #quote=69.99, #membershipType=6, #promocode='1', #giftCertificateCode='1'
That returns 1, as it should.
But in C#, when I try to pass in the parameters #quote, #membershipType, #promocode, #giftCertificateCode with the exact same values, I get an exception in the code. It reads '69.99' is out of range.
In my table and in the stored procedures, I have the columns as floats. I just don't understand why passing in a C# double is giving me a precision error. Can anybody advise?
Edit:
Here's the C# code:
IDataAccess dataAccess = _dataAccessService.GetDataAccess();
IDataConnection connection = _dataAccessService.GetConnection(Connectionstring);
var operation = new DataOperation("PriceConfirm");
operation.Parameters.Add(new DataParameter("#quote", DbType.Double, quote));
operation.Parameters.Add(new DataParameter("#membershipType", DbType.Int32, membership));
operation.Parameters.Add(new DataParameter("#promocode", DbType.String, promocode));
operation.Parameters.Add(new DataParameter("#giftCertificateCode", DbType.String, giftcode));
IResultSet reader = dataAccess.ExecuteResultSet(connection, operation, ResultSetType.Reader);
Reader is null after it tries to execute the operation. It throws an exception saying that "Data Parameter '69.99' is out of range."
OK you should NOT ever have numerics stored as floats if you do math calculations on them. You should fix your tables before doing anything else. Floats are exdtremely poor to use as they are inexact, always.
In your sp (which should not begin with sp_ BTW - that is for system procs and SQL Server will check the master datbase first every time it is run which is a waste of processing time)
Your sp does not accept float, it is defined as a decimal(4,2). Run Profiler and see what the C# code is trying to send to the database. I'll bet it is sending more than 2 decimal places.
It turns out changing the type to Decimal(18,4) does the trick. Apparently float types in SQL Server 2008 are kind of buggy. It would have worked sooner for me if I had remembered to change the DbType to Decimal in the C# code.

Categories