Parameter does not exist as a stored procedure parameter - c#

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.

Related

Passing a DataSet in to a T-SQL stored procedure as a parameter from C#

I am attempting to pass a populated dataset from C# to a SQL Server stored procedure parameter, but I'm having trouble.
Here is my C# code:
if (tblNoMatch.Rows.Count > 0)
{
pge.dbconn.ExecuteNonQuery("dbo.MySproc",
new SqlParameter("#MyTableParam", tblNoMatch),
new SqlParameter("#IsProcessed", "2")
);
pge.dbconn.ShutDown();
}
where tblNoMatch is type DataSet, and populated with a column ID. The dataset variable is filled with 40 rows of ID values.
Here is my SQL end:
IF TYPE_ID(N'MyTable') IS NULL
CREATE TYPE dbo.MyTable AS TABLE(BatchID INT);
GO
ALTER PROCEDURE [dbo].[MySproc]
#MyTableParam AS dbo.MyTable READONLY,
#IsProcessed [smallint] = 0
AS
IF (SELECT COUNT(*) FROM #MyTableParam) > 0
--Process Records from Batch
BEGIN
UPDATE [dbo].[MyTable]
SET [IsProcessed] = ISNULL(#IsProcessed, IsProcessed)
WHERE [ID] IN (SELECT ID FROM #MyTableParam)
END
When I sniff the throughput with SQL Server Profiler tool, I don't even see #MyTableParam getting passed, and on the SQL Server end, it's getting ignored entirely.
What am I doing wrong here?
Many thanks in advance!
EDIT:
I made this alteration as I know the parameter needs to be of type Structured, but this unfortunately did not do the trick for me either:
if (tblNoMatch.Rows.Count > 0)
{
var tblParameter = new SqlParameter
{
ParameterName = "#MyTableParam",
SqlDbType = SqlDbType.Structured,
Value = tblNoMatch
};
pge.dbconn.ExecuteNonQuery("dbo.MySproc", tblParameter,
new SqlParameter("#IsProcessed", "2"));
pge.dbconn.ShutDown();
}
What else am I missing here?
Try specifying the TypeName as follows...
tblParameter.TypeName = "dbo.MyTable";

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
)

How to take input from SQL stored procedure to a return statement

alter procedure [dbo].[XXX]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date,
#total int out
)
begin
select #total = COUNT(*)
from AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select cc.BCampaignID
from BeaconCampaign cc, VendorWorkStation vw
where cc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)
return #total
end
The above code shows the stored procedure that return an integer value from SQL Server
ObjectParameter Output = new ObjectParameter("total", typeof(Int32));
var resBC = this.Context.getTotalSentBeaconCampaign(VendorWorkstationID, sdate,edate,Output).FirstOrDefault();
The above code shows how I am passing parameters and retrieving the value on the C# side
While running the code I am getting following error
The data reader returned by the store data provider does not have
enough columns for the query requested.
What could be the possible cause for this error?
Entity Framework cannot support Stored Procedure Return scalar values out of the box.To get this to work with Entity Framework, you need to use "Select" instead of "Return" to return back the value.
More Ref : http://www.devtoolshed.com/using-stored-procedures-entity-framework-scalar-return-values

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.

update error handling in C#

I have a customer table in sqlserver which contains a rowversion field and I am incrementing it everytime I update the record,
I just have to check with
if(Customer.rowversion=#roeversion ) where customerID=#customerID
execute the update.
else RAISERROR('Update cannot be executed. There is a row version conflict.', 16, 1)
So have to now pass an out param from my c# code and return the error value. and also
- Get the Error Code for the statement just executed.
SELECT #ErrorCode=##ERROR
So how should I return the value from SQLSERVER update query into my c# code so that I can display the message.
If you're calling your sproc via ado.NET, then the SqlParameter you pass to the sproc would be set up like this:
SqlParameter P = new SqlParameter("Name of your column", SqlDbType.Int);
P.Direction = ParameterDirection.Output;
//call your sproc
int result = (int)P.Value;
EDIT
Since you're using Linq-to-SQL, adding this sproc into the methods sections should create a c# method signature for this sproc with the out parameter added for you.
If you do not already, you should have your database code in a stored procedure. The stored procedure would look something like:
CREATE PROCEDURE s_my_procedure
#RowVersion int ,
#CustomerID int ,
... additional fields here
#ErrorCode INT OUTPUT
AS
IF EXISTS(SELECT 1
FROM Customer
WHERE RowVersion = #RowVersion
AND CustomerID = #CustomerID)
BEGIN
UPDATE Customer
SET ...
WHERE RowVersion = #RowVersion
AND CustomerID = #CustomerID
SET #ErrorCode = 0
END
ELSE
BEGIN
SET #ErrorCode = 1234 -- Something meaningful to your app
END
You should try to avoid raising errors whenever possible.
Then, assuming you have a stored procedure executed by a command:
cmd.ExecuteNonQuery();
int ErrorCode = 0;
// Note that if you are not sure about your sp, you should test this for dbnull.value first
ErrorCode = Convert.ToInt32(cmd.Parameters["#ErrorCode"].Value);

Categories