I need to enter some value in the textbox end save it to the database. But if there is a duplicate value then the value must not be saved.
Basically, string lvl is successfully passed to the WebMethod from front-end via ajax.
Procedure getDuplicate is a simple select that checks if there is a value of lvl is already stored in the database. And InsertObject procedure inserts the value in the database. If the value(lvl) exists then the ID of that value is return and stored in the Count integer.
The problem is if Count is returned with id number then if statement works, and if there is no value in the database Count just does not receive any values and the procedure fails and goes straight to the catch part of the code.
I think there's a problem with the returning type from a database when there is no value in it. It is not INT or something. Can anyone help, please?
[WebMethod(EnableSession = true)]
public static void GetCollection(string lvl)
{
string conn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
try
{
connection.Open();
SqlCommand cmdCount = new SqlCommand("getDuplicate", connection);
cmdCount.CommandType = CommandType.StoredProcedure;
cmdCount.Parameters.AddWithValue("@ObjekatName", lvl);
int count = (int)cmdCount.ExecuteScalar();
if (count > 0)
{
}
else
{
SqlCommand cmdProc = new SqlCommand("InsertObjekat", connection);
cmdProc.CommandType = CommandType.StoredProcedure;
cmdProc.Parameters.AddWithValue("@ObjekatName", lvl);
cmdProc.ExecuteNonQuery();
//strMsg = "Saved successfully.";
}
}
catch
{
}
finally
{
connection.Close();
}
return;
getDuplicate procedure
ALTER PROCEDURE [dbo].[GetDuplicate]
@ObjekatName nvarchar(20)
AS
BEGIN
SET NOCOUNT ON
SELECT TOP 1000 [ObjekatID]
,[ObjekatName]
FROM [MyApp].[dbo].[Objekat]
WHERE ObjekatName = @ObjekatName
END
Please change your GetDuplicate proc as below. It will always return a value.
CREATE PROCEDURE [dbo].[GetDuplicate]
@name nvarchar(20)
AS
BEGIN
DECLARE @duplicateCount int
SELECT @duplicateCount=count(*) FROM [dbo].[employee] WHERE name = @name
RETURN @duplicateCount
END