I was given this function
CREATE FUNCTION [dbo].[GET_WEBGIS_ISSUE_NUM]
()
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @v_new_num int, @v_new_issue_num varchar(50);
SET @v_new_num = (SELECT COUNT(*) + 1
FROM [dbo].[WEBGIS_ISSUE]
WHERE [ISSUE_NUM] LIKE CONCAT(FORMAT(GETDATE(), 'yyMM'), '%'));
IF @v_new_num < 10
SET @v_new_issue_num = CONCAT(FORMAT(GETDATE(), 'yyMM'), '00', @v_new_num);
ELSE IF @v_new_num < 100
SET @v_new_issue_num = CONCAT(FORMAT(GETDATE(), 'yyMM'), '00', @v_new_num);
ELSE
SET @v_new_issue_num = CONCAT(FORMAT(GETDATE(), 'yyMM'), @v_new_num);
RETURN @v_new_issue_num
END;
I tried calling it from the following C# code
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[NEPS].[dbo].[GET_WEBGIS_ISSUE_NUM]";
//add any parameters the stored procedure might require
if (cmd.Connection.State == ConnectionState.Closed) //cmd.Connection.Open();
{
cnn.Open();
var o = cmd.ExecuteScalar();
//blabla
cnn.Close();
}
but when I debug the code, I kept on receiving null.
Notes: the connection is ok, it is connected, when I tried changing the function's name it yields an error and when I checked through the SQL Server it also returns an appropriate return value.
cmd.CommandType = CommandType.StoredProcedure?GET_WEBGIS_ISSUE_NUMisn't a Stored Procedure; it's a scalar function...CommandType.Textand runSELECT * FROM dbo.GET_WEBGIS_ISSUE_NUM()- but this really BADLY smells like a hack doing somewhat the same thing as anIDENTITYcolumn - just not properly and safely........SEQUENCEwould be a better choice if it is trying to serve a purpose similar to anIDENTITYbut for multiple tables.SEQUENCEis available on all supported (included those in extended support) versions of SQL Server, so if that is what you are after I see no reason why you wouldn't use it.SELECT dbo.GET_WEBGIS_ISSUE_NUM(). Although why this function even exists is another question. At the very least it should be an inline Table Valued Function, which is much faster. You also need to dispose your connection and command objects withusing. And you don't needif (cmd.Connection.Statethere is no reason for it to be open if you just created itCOUNT(*) + 1is highly suspect, as it seems this would easily break if records are ever removed (even without concurrency), so you'd have to commit to a table that is absolutely append-only. An approach based onMAXseems more stable (but still not safe under concurrency on its own, mind you).