I am trying to insert data into a SQL Server database by calling a stored procedure, but I am getting the error
Procedure or function 'sp_Lab_InsertBiologicalPersonnel' expects parameter '#IcNumber', which was not supplied
My stored procedure is called sp_Lab_InsertBiologicalPersonnel. I already check many time if there something missing, but still get same error, even make comparison with old code which is working. But for my code it say that error.
This is my C# code
public static PostApiResponse InsertBiologicalPersonel(Adapter ad, BiologicalPersonelInsert request, int creatorUserId)
{
var response = new PostApiResponse();
try
{
using (SqlCommand command = new SqlCommand("sp_Lab_InsertBiologicalPersonnel", ad.SQLConn, ad.SQLTran))
{
SqlParameter Param = new SqlParameter();
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter() { Value = request.biologicalId, ParameterName = "#biologicalId" });
command.Parameters.Add(new SqlParameter() { Value = request.IcNumber, ParameterName = "#IcNumber" });
command.Parameters.Add(new SqlParameter() { Value = request.Position, ParameterName = "#Position" });
command.Parameters.Add(new SqlParameter() { Value = creatorUserId, ParameterName = "#IdUserCreator" });
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
response.ResponseMessage = reader.GetString(0);
response.ReturnCode = reader.GetInt32(1);
response.Id = Convert.ToInt32(reader.GetValue(2));
}
reader.Close();
}
}
}
catch (Exception e)
{
throw e;
//string context = Common.ToStr(System.Web.HttpContext.Current);
//clsErrorLog.ErrorLog(context, e);
}
return response;
}
And this is my stored procedure:
ALTER PROCEDURE [dbo].[sp_Lab_InsertBiologicalPersonnel]
#biologicalId INT,
#IcNumber INT ,
#Position NVARCHAR(50),
#IdUserCreator INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ReturnCode Int
DECLARE #ReturnMessage NVARCHAR(200)
DECLARE #Identity INT
INSERT INTO [dbo].[Lab_BiologicalPersonnel]
([Id]
--,[Name]
,[IcNumber]
,[Position]
,[IdUserCreator]
,[IsDeleted]
,[IsEnabled])
VALUES
(#biologicalId
--,#Name
,#IcNumber
,#Position
,#IdUserCreator
,0
,1)
IF ##ROWCOUNT = 0
BEGIN
SET #ReturnCode = 1
SET #ReturnMessage = 'Insert Fail'
SET #Identity = 0
END
ELSE
BEGIN
SET #ReturnCode = 0
SET #ReturnMessage = 'Insert Success'
SET #Identity = (SELECT SCOPE_IDENTITY())
END
SELECT #ReturnMessage, #ReturnCode, #Identity
END
Please help me explain in quite simple, I'm a newbie in programming.
I am building a .NET Core 3.1 Web API that uses stored procedures.
One of the stored procedures takes input and select values from a form and returns a ticket once the form is submitted in the front end.
My SQL Server stored procedure that looks like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CallSummaryAddO]
#SedonaUser NVarCHar(100),
#SystemID Int,
#ProblemID Int,
#ResolutionID Int,
#NextStepID Int,
#CustomerComments NVaRChar(1000),
#TechNotes NVaRChar(1000),
#CustomerOnCall NVarChar(200),
#CustomerCallBackPhone NVarChar(15)
AS
DECLARE #ServiceTicketID Int,
#CustomerID Int,
#CustomerSiteID Int,
#NextTechID Int,
#TicketStatus NVarCHar(10),
#Today DateTime,
#ClosedDate DateTime,
#ServiceLevel Int,
#Route Int,
#AutoNotify NVarChar(320)= '',
#CustomerBillID Int,
#ServiceCoordinator Int = 1,
#TicketNumber Int,
#TicketNumberAdded Int
EXEC Sandbox.dbo.Service_Ticket_Next #TicketNumber Output
SET #TicketNumberAdded = #TicketNumber
SET #TicketStatus = CASE WHEN #ResolutionID = 1 THEN 'OP' ELSE 'CL' END
SET #ClosedDate = CASE WHEN #ResolutionID = 1 THEN '1899-12-30' ELSE GETDATE() END
SELECT
#CustomerID = S.Customer_id,
#CustomerSiteID = S.Customer_Site_id,
#ServiceLevel = Service_Level_Id,
#Route = Route_Id,
#CustomerBillID = Ste.Customer_Bill_Id
FROM
Sandbox.dbo.ar_customer_system S
INNER JOIN
Sandbox.dbo.ar_customer_site ste ON ste.Customer_Site_Id = S.Customer_Site_Id
WHERE
Customer_System_Id = #SystemID
SET #Today = GETDATE()
SET #ServiceCoordinator = #NextStepID
INSERT INTO Sandbox.dbo.[SV_Service_Ticket]
([Ticket_Status],[Ticket_Number],[Customer_Id],[Customer_Site_Id],[Customer_System_Id]
,[Multiple_Systems],[Creation_Date],[Requested_By],[Requested_By_Phone],[Problem_Id]
,[Scheduled_For],[Last_Service_Tech_Id],[Estimated_Length],[Resolution_Id],[Billable]
,[Billed],[Equipment_Charge],[Labor_Charge],[Other_Charge],[TaxTotal],
[Regular_Hours],[Overtime_Hours],[Holiday_Hours],[Trip_Charge],[Invoice_Id],[Regular_Rate],[Overtime_Rate],[Holiday_Rate],[Bypass_Warranty],[Bypass_ServiceLevel],[IsInspection]
,[ClosedDate],[Manual_Labor],[Service_Company_Id],[Priority_Id],[Category_Id],[Expertise_Level]
,[Entered_By],[Invoice_Contact],[Signer],[Remittance],[Signature_Image],[Payment_Received]
,[Sub_Problem_Id],[Service_Level_Id],[UserCode],[Edit_Timestamp],[PO_Number],[CustomerComments],[Number_Of_Dispatches],[Route_Id]
,[Sub_Customer_Site_ID],[Customer_CC_Id],[Customer_Bank_Id],[Ticket_Status_Id],[Customer_EFT_Id],[Auto_Notify]
,[Customer_Bill_Id],[Customer_Contact_Id],[Requested_By_Phone_Ext] ,[Inspection_Id],[Service_Ticket_Group_Id]
,[Service_Coordinator_Employee_Id],[Resolved_Date],[Inspection_Incremented],[OPT_rowguid],[Bypass_TicketServiceCompany]
,[EntrySource])
VALUES
(#TicketStatus, #TicketNumber,#CustomerID, #CustomerSiteID, #SystemID,
'N', #Today, #CustomerOnCall, #CustomerCallBackPhone, #ProblemID,
'1899-12-30', 1, 60, #ResolutionID, 'N',
'', 0,0,0,0,
0,0,0,0,1,0,0,0,'N','N','N',
#ClosedDate,'N',56,2,2,3,
#SedonaUser,'','','N','0x4E6F205369676E6174757265204F6E2046696C65','N',
1,#ServiceLevel,#SedonaUser,#Today,'', #CustomerComments,0,#Route,
1,0,0,1,1,#AutoNotify,#CustomerBillID,1,'',1,1,#ServiceCoordinator,#ClosedDate,'N',NewID(),'N','Service')
SET #ServiceTicketID = ##IDENTITY
INSERT INTO Sandbox.dbo.SV_Service_Ticket_Notes (Service_Ticket_Id, Notes, Access_Level, UserCode, Entered_Date, Edit_UserCode, Edit_Date, Is_Resolution)
VALUES (#ServiceTicketID, #TechNotes,1,#SedonaUser, #Today, #SedonaUser, #Today, Case When #TicketStatus = 'CL' then 'Y' else 'N' end)
DECLARE #UserComments NVarChar(100)
SET #UserComments = 'Added Service Ticket ' + CONVERT(NVarChar,#TicketNumber)
INSERT INTO Sandbox.dbo.SY_Edit_Log (UserCode, Edit_Timestamp, TableName, Edit_Type_AUD, KeyField, KeyData, UserComments, SystemComments, Edit_Column_Name, OldData, NewData)
VALUES (#SedonaUser, #Today, 'SV_Service_Ticket', 'A', 'Ticket_Number', #TicketNumber, #UserComments, '','','','')
IF #TicketStatus = 'CL'
BEGIN
SET #UserComments = 'Closed Service Ticket ' + CONVERT(NVarChar,#TicketNumber)
INSERT INTO Sandbox.dbo.SY_Edit_Log (UserCode, Edit_Timestamp, TableName, Edit_Type_AUD, KeyField, KeyData, UserComments, SystemComments, Edit_Column_Name, OldData, NewData)
VALUES (#SedonaUser, #Today, 'SV_Service_Ticket', 'U', 'Ticket_Number', #TicketNumber, #UserComments, '','','','')
END
RETURN #TicketNumberAdded
My repository looks like this:
public async Task<CallSummaryAddResult> InsertCallSummaryAddResult(CallSummaryAddResult callSummaryAddResult)
{
using (SqlConnection sql = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.CallSummaryAddO", sql))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#SedonaUser", SqlDbType.NVarChar)).Value = callSummaryAddResult.SedonaUser;
cmd.Parameters.Add(new SqlParameter("#SystemID", callSummaryAddResult.SystemID));
cmd.Parameters.Add(new SqlParameter("#ProblemID", callSummaryAddResult.ProblemID));
cmd.Parameters.Add(new SqlParameter("#ResolutionID", callSummaryAddResult.ResolutionID));
cmd.Parameters.Add(new SqlParameter("#NextStepID", callSummaryAddResult.NextStepID));
cmd.Parameters.Add(new SqlParameter("#CustomerComments", SqlDbType.NVarChar)).Value = callSummaryAddResult.CustomerComments;
cmd.Parameters.Add(new SqlParameter("#TechNotes", SqlDbType.NVarChar)).Value = callSummaryAddResult.TechNotes;
cmd.Parameters.Add(new SqlParameter("#CustomerOnCall", SqlDbType.NVarChar)).Value = callSummaryAddResult.CustomerOnCall;
cmd.Parameters.Add(new SqlParameter("#CustomerCallBackPhone", SqlDbType.NVarChar)).Value = callSummaryAddResult.CustomerCallBackPhone;
//cmd.Parameters.Add(new SqlParameter("#TicketNumber", SqlDbType.Int));
//cmd.Parameters["#TicketNumber"].Direction = ParameterDirection.Output;
await sql.OpenAsync();
await cmd.ExecuteNonQueryAsync();
_callSummaryAddResults.Add(callSummaryAddResult);
return callSummaryAddResult;
}
}
}
When I execute this in SSMS, I am getting a new ticket number, but in code, I am only getting 0 back. I want to display the actual returned ticket number and not a 0 or 1 (success or failure).
My job is to return the TicketNumber and display this to the end-user once available. How can I make this happen?
Thanks in advance.
I am stuck in a problem. i am getting error "Procedure or function 'SP_RPT_User' expects parameter '#deptName', which was not supplied." in c# application while parameter is provided. even i copied and replaced the name. still no success.
public DataTable SP_RPT_User(int loggedid, String deptName, String OfficeName, String empType)
{
int updatedrows = 0;
DataTable table = new DataTable();
try
{
cCommand = new System.Data.SqlClient.SqlCommand("SP_RPT_User", connection);
cCommand.CommandType = CommandType.StoredProcedure;
cCommand.Parameters.Add("#loggedId", SqlDbType.Int).Value = loggedid;
cCommand.Parameters.Add("#deptName", SqlDbType.NVarChar, 200).Value = deptName;
cCommand.Parameters.Add("#OfficeName", SqlDbType.VarChar, 150).Value = OfficeName;
cCommand.Parameters.Add("#empType", SqlDbType.VarChar, 150).Value = empType;
cCommand.CommandTimeout = 90000;
connection.Open();
updatedrows = cCommand.ExecuteNonQuery();
using (var da = new SqlDataAdapter(cCommand))
{
cCommand.CommandType = CommandType.StoredProcedure;
da.Fill(table);
}
}
catch (Exception Ex)
{
connection.Close();
// return -100;
}
finally
{
connection.Close();
}
return table;
}
Stored Procedure
ALTER PROCEDURE [dbo].[SP_RPT_User]
-- Add the parameters for the stored procedure here
#loggedId int,
#deptName NVarChar(200),
#OfficeName varchar(150),
#empType varchar(150)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #sql nvarchar(max);
set #sql ='SELECT ...'; // here is one query
if(#deptName != '')
set #sql = #sql + ' and dbo.TB_Department.name like ''%'+#deptName+'%''';
Declare #params nvarchar(500)
SELECT #params ='#loggedId int,'+
'#deptName NVarChar(200),'+
'#OfficeName varchar(150),'+
'#empType varchar(150)'
exec sp_executesql #sql, #params,#loggedId,#deptName,#OfficeName,#empType;
END
Can anyone help. thanks in advance.
i am using sql server 2014 and vs2015.
The educated guess I have is that deptName value in C# is null while you execute the query. In such case you should pass DBNull.Value to have null as parameter value:
var param = cCommand.Parameters.Add("#deptName", SqlDbType.NVarChar, 200);
param.Value = deptName ?? DBNull.Value;
From your procedure I see that you compare with empty string so use ?? string.Empty to satisfy that condition.
I've tried everything to get this to work and I know I'm missing something very simple.
I have a method that calls a stored procedure to update a record in a table.
It just so happens that one of the parameters is nullable in the database and the program value for it comes in as an empty string ("") for the vehicleNo column in this particular kind of situation.
All the other records get updated except if an empty string comes in and I try and update the record with the stored procedure.
Can someone please point out what I need to add to make the stored procedure or code work correctly?
Below the code, I've tried executing the stored procedure with hard coded values, but neither updates with the ImageID.
Stored procedure
ALTER PROCEDURE [dbo].[SPR_UPDATE_IMAGEID]
#ticketNo int,
#vehicleNo varchar(6) = NULL,
#imageID varchar(20)
AS
BEGIN
IF ((#vehicleNo = '') OR (#vehicleNo IS NULL))
BEGIN
UPDATE dbo.HH_FuelTkt
SET Image_ID = #imageID
WHERE Ticket_No = #ticketNo
AND Vehicle_No = NULL
END
ELSE
BEGIN
UPDATE dbo.HH_FuelTkt
SET Image_ID = #imageID
WHERE Ticket_No = #ticketNo
AND Vehicle_No = #vehicleNo
END END
C# code:
public static bool UpdateData(int ticketNo, string vehicleNo, string imageID)
{
int retValue = 0;
try
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HHInboundSqlConnection"].ToString()))
{
SqlCommand cmd = new SqlCommand("SPR_UPDATE_IMAGEID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ticketNo", ticketNo);
cmd.Parameters.AddWithValue("#vehicleNo", vehicleNo);
cmd.Parameters.AddWithValue("#imageID", imageID);
cmd.Connection.Open();
retValue = cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
throw e;
}
return (retValue > 0);
}
Manual stored procedure execution #1:
DECLARE #return_value int
EXEC #return_value = [dbo].[SPR_UPDATE_IMAGEID]
#ticketNo = 147058,
#vehicleNo = N'''''',
#imageID = N'39084'
SELECT 'Return Value' = #return_value
Manual stored procedure execution #2:
DECLARE #return_value int
EXEC #return_value = [dbo].[SPR_UPDATE_IMAGEID]
#ticketNo = 147058,
#vehicleNo = N'NULL',
#imageID = N'39084'
SELECT 'Return Value' = #return_value
IF ((#vehicleNo = '') OR (#vehicleNo IS NULL))
BEGIN
UPDATE dbo.HH_FuelTkt
SET Image_ID = #imageID
WHERE Ticket_No = #ticketNo
**AND Vehicle_No = NULL**
END
change the
AND Vehicle_No = NULL
to
AND Vehicle_No IS NULL
Normally on SQL check nullable value we use IS NULL instead of = NULL
I have an application which changes fields in a table. It's a simple form where the user can change the company associated with a group.
.NET
public static string EditGroup(vw_Group_Model editGroup)
{
string outcome = "";
if (editGroup.RowType == "ALF")
{
try
{
using (SqlConnection conn = AlfOnlineConnection())
{
conn.Open();
UserManager.Models.vw_Group_Model model = new vw_Group_Model();
using (var command = new SqlCommand("sp_UserManager_EditGroup", conn))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#CompanyId", SqlDbType.Int).SqlValue = editGroup.companyId;
command.Parameters.Add("#GroupId", SqlDbType.Int).SqlValue = editGroup.groupId;
//command.Parameters.Add("#CompanyName", SqlDbType.NVarChar).SqlValue = editGroup.selected_company;
//command.Parameters.Add("#GroupName", SqlDbType.NVarChar).SqlValue = editGroup.groupName;
command.Parameters.Add("#StartDate", SqlDbType.DateTime).SqlValue = editGroup.StartDate;
command.Parameters.Add("#EndDate", SqlDbType.DateTime).SqlValue = editGroup.EndDate;
switch (editGroup.IsActive)
{
case true:
command.Parameters.Add("#isactive", SqlDbType.TinyInt).SqlValue = 1;
break;
case false:
command.Parameters.Add("#isactive", SqlDbType.TinyInt).SqlValue = 0;
break;
}
int rowsEdited = command.ExecuteNonQuery();
if (rowsEdited == 1)
{
outcome = "Row successfully edited.";
}
}
}
}
catch (SqlException ex)
{
return ex.ToString();
}
}
T-SQL
USE [BradOnline]
GO
/****** Object: StoredProcedure [dbo].[sp_UserManager_EditGroup] Script Date: 01/17/2013 13:11:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[sp_UserManager_EditGroup]
#GroupId INT,
#CompanyId INT,
--#GroupName NVARCHAR(50),
--#CompanyName NVARCHAR(50),
#StartDate DATETIME,
#EndDate DATETIME,
#isactive TINYINT
AS
BEGIN
DECLARE #AccountManagerId uniqueidentifier
SET #AccountManagerId = '7A1DC75D-2628-4F8D-A376-9382A0762568'
--(SELECT G.AccountManagerId FROM dbo.aspnet_Custom_Groups AS G
-- WHERE Id = #GroupId)
--DECLARE #CompanyId BIGINT
--SET #CompanyId = (SELECT MAX(c.Id) FROM dbo.aspnet_Custom_Companies AS c
-- WHERE c.Name = #CompanyName)
UPDATE
[dbo].[aspnet_Custom_Groups]
SET
--[Name] = #GroupName,
[StartDate] = #StartDate,
[EndDate] = #EndDate,
[IsActive] = #isactive,
[AccountManagerId] = NULL,
[CompanyId] = #CompanyId
WHERE
[Id] = #GroupId
END
In the SQL if I hard-code the values for the update it works, but if i pass the values in it doesn't. I have been looking at it for ages but haven't gotten anywhere. The parameters in my application contain values when I check with a breakpoint
Instead of setting your parameter values through SqlParameter.SqlValue, try using SqlParameter.Value like below.
command.Parameters.Add("#CompanyId", SqlDbType.Int).Value = editGroup.companyId;