How to update Columns if value is not NULL - sql

I want to update any columns of table TBL_Log if value entered from C# is not NULL. Here is my stored procedure:
Alter PROCEDURE [dbo].[SP_Update_User]
(#User_id as int,#User_Names as nvarchar(max),#End as char(8),#Start as nvarchar(max) ,#Count as int)
AS
BEGIN
UPDATE [dbo].[TBL_Log]
SET User_Names = #User_Names
,[Start] = #start
,[End] = #End
,[Count] = #Count
where User_id = #User_id
END
I have tried to make this work but have not been successful.
code in class D1:
public static DataSet Update_User(int #User_id, string #User_Names, string #End, string #Start, int #Count)
{
SqlConnection myConnection = new SqlConnection(strConecctionString);
SqlDataAdapter sqlcmd = new SqlDataAdapter("SP_Update_UserData_Bot", myConnection);
sqlcmd.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parameterID_category_ID = new SqlParameter("#User_id", SqlDbType.Int);
parameterID_category_ID.Value = User_id;
sqlcmd.SelectCommand.Parameters.Add(parameterID_category_ID);
SqlParameter parameterID_Part_ID = new SqlParameter("#User_Names", SqlDbType.Int);
parameterID_Part_ID.Value = User_Names;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Part_ID);
SqlParameter parameterID_Series_ID = new SqlParameter("#End", SqlDbType.Char);
parameterID_Series_ID.Value = End;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Series_ID);
SqlParameter parameterID_Model_ID = new SqlParameter("#start", SqlDbType.NVarChar);
parameterID_Model_ID.Value = start;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Model_ID);
SqlParameter parameterID_Count = new SqlParameter("#Count", SqlDbType.Int);
parameterID_Count.Value = Count;
sqlcmd.SelectCommand.Parameters.Add(parameterID_Count);
sqlcmd.SelectCommand.CommandTimeout = int.MaxValue;
DataSet DS = new DataSet();
sqlcmd.Fill(DS);
return DS;
}

This will update only the values that are not null. If the value is null, the column is updated back to its own value.
UPDATE [dbo].[TBL_Log]
SET User_Names = isnull(#User_Names, User_Names)
, [Start] = isnull(#start, [Start])
, [End] = isnull(#End, [End])
, [Count] = isnull(#Count, [Count])
where User_id = #User_id

You should show your .Net code. Probably the best place to add the check is in .NET and don't call the stored procedure if the value you are worried about is NULL.
Also you must specify which value shouldn't be null, but assuming you meant any of them you can do:
IF (#User_Names IS NULL OR #start IS NULL OR #End IS NULL OR #Count IS NULL OR #User_Id IS NULL)
BEGIN
RETURN
END
That will exit of the stored procedure if any of the parameters is null without updating the table
Given you c# code you can either don't call the stored procedure when a value is null or throw an exception. Also you should consider using DateTime instead of string for date values.
You can do the following in your c# code:
if (#User_Names == null || #End == null || #Start == null)
return;
Or preferably
if (#User_Names == null || #End == null || #Start == null)
throw new ArgumentNullException();
You can even check each parameter individually and pass its name as parameter to the Exception to give a meaningful error message.

Your commented out logic is fine:
UPDATE [dbo].[TBL_Log]
SET User_Names = #User_Names,
[Start] = #start,
[End] = #End,
[Count] = #Count
where User_id = #User_id and
(#User_Names is not null and
#AkharinBazdid is not null and
#Pid_Bazdid IS NOT NULL and
#C_Bazdid IS NOT NULL
);
You can also use IF if you prefer.
Notes:
Don't use SQL keywords and reserved words as column names. The escape characters just get in the way.
If start and end are date/times, then use the appropriate types. Don't use strings.

Related

Fetch stored procedure value

I have a table RhSeq which contains the following columns:
ScoTable (PK, varchar(20),not NULL)
ScoColonne (PK, varchar(50), not NULL)
ScoSequence (int, not NULL)
ScoDescription (varchar(100), not NULL)
I have a stored procedure which, given ScoTable and ScoColonne, increments ScoSequence and returns the incremented ScoSequence value:
EDITED - Here's the full stored procedure
CREATE PROCEDURE [dbo].[usp_RhSeqNextVal]
#table VARCHAR (20), #colonne VARCHAR (30), #sequence_id INT OUTPUT
AS
SET NOCOUNT ON
SET #sequence_id = -1
DECLARE #transaction AS BIT
SET #transaction = 0;
IF 0 = ##TRANCOUNT
BEGIN
BEGIN TRAN
SET #transaction = 1;
END
UPDATE dbo.RhSeq
SET ScoSequence = CASE WHEN Right(#colonne,1) = '-' THEN
ScoSequence - 1
ELSE
ScoSequence + 1
END
WHERE ScoTable = #table
AND ScoColonne = #colonne
SELECT #sequence_id = ScoSequence
FROM dbo.RhSeq
WHERE ScoTable = #table
AND ScoColonne = #colonne
IF 1 = #transaction
BEGIN
COMMIT TRAN
END
In Visual Studio, if I right click on the stored procedure (in Server Explorer) and choose 'Execute', I enter values for ScoTable and ScoColonne and set sequence_id to null and it executes fine, returning the new incremented sequence_id value. So no problem with the stored procedure.
The problem I have is when I try to get the returned sequence_id inside my code.
SqlParameter param1 = new SqlParameter("#ScoTable", "MyTable");
SqlParameter param2 = new SqlParameter("#ScoColonne", "MyColumn");
SqlParameter param3 = new SqlParameter("#sequence_id", DBNull.Value);
var numeroSequence = db.Database.SqlQuery<RhSeq>("usp_RhSeqNextVal #ScoTable,#ScoColonne, #sequence_id", param1, param2,param3).ToList();
I get an error
System.Data.Entity.Core.EntityCommandExecutionException: A member of the type, 'ScoTable', does not have a corresponding column in the data reader with the same name
From my understanding, the error comes from RhSeq, since the stored procedure returns only sequence_id, which is an int, it cannot create a RhSeq object with it. I try to cast the result to an int, but it's still not working.
How can I store the sequence_id returned by the stored procedure into my var numeroSequence?
Had a similar issue in LinqToSQL. Selecting #sequence_id in the procedure after setting it did the job:
In your SP after:
SELECT #sequence_id = ScoSequence
FROM dbo.RhSeq
WHERE ScoTable = #table
AND ScoColonne = #colonne
Add:
SELECT #sequence_id
And then of course:
db.Database.SqlQuery<int>...

How to use the return value of stored procedure in asp.net?

I use this stored procedure for get the number of records
ALTER PROCEDURE [dbo].[Asbabbazi_A]
#count int output
AS
BEGIN
if(#count=0)
set #count =( select count(*) from dbo.Table_asbabbazi where (active= 0))
end
now I want use the #count in my project.I wrote this codes for use the #count in method.
SqlConnection con = new SqlConnection(constr);
cmd.Connection = con;
con.Open();
DataAdapter.SelectCommand = cmd;
DataSet ds = new DataSet("haftehbazardb");
SqlCommandBuilder bldr = new SqlCommandBuilder(DataAdapter);
SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
DataAdapter.Fill(ds, Table_asbabbazi);
countrecords = (int)returnParameter.Value;
this codes have no error but when i use the (countrecords ) in my project the value of (countrecords ) is zero that is not right .
Please help
If you want to get the value as the output of the stored procedure, you will need to return it.
ALTER PROCEDURE [dbo].[Asbabbazi_A]
#count int output
AS
BEGIN
if(#count=0)
set #count =( select count(*) from dbo.Table_asbabbazi where (active= 0))
return #count
end
You are confusing output parameters with a return value.
Return value is generally used to indicate the status of your procedure, it will be 0 if not specified, e.g.
CREATE PROCEDURE dbo.TestProc #Out INT OUTPUT
AS
BEGIN
BEGIN TRY
SET #Out = 1 / 0;
RETURN 0;
END TRY
BEGIN CATCH
SET #Out = 0;
RETURN 1;
END CATCH
END
Then calling this with T-SQL;
DECLARE #out INT, #return INT;
EXECUTE #Return = dbo.TestProc #out OUT;
SELECT [Return] = #return, [out] = #out;
Will give:
Return | out
-------+-----
1 | 0
Since 0 is the default return value, this is why you are getting 0 out from returnParameter, you need to use ParameterDirection.Output:
SqlParameter returnParameter = cmd.Parameters.Add("count", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.Output;

Record in table is not updated when another record is null

I already posted the similar question by with different interpretation.
I'm looking for the solution to the following problem:
I have a stored procedure that is called from my code.
I need to update a record in my table and set it to either 1 or 0. It is a bit datatype.
My stored procedure accepts 3 parameters: region, isActive and Number:
This is my stored procedure:
ALTER PROCEDURE [dbo].[SPU_UpdateEmai]
#region char(2),
#isoNum varchar(10),
#isActive bit
AS
BEGIN
SET NOCOUNT ON;
UPDATE MyTable
SET isActive = #isActive, updatedate = GETDATE()
WHERE region = #region AND isonumber = #isoNum
END
When #isoNumber is not empty, then I can update my isActive field, if #isoNumber is empty, nothing happens.
When simply executing update:
UPDATE ActivateEmailSendToIso
SET isActive = 0, updatedate = GETDATE()
WHERE region = '04' AND isonumber is null
everything is fine. But when running the code, update does not happen. This is the code:
using (SqlCommand cmd = new SqlCommand("SP_UpdateEmail", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#region", actData.Region);
//cmd.Parameters.AddWithValue("#isoNum", actData.IsoNumber);
cmd.Parameters.AddWithValue("#isoNum", (actData.Equals(String.Empty)) ? (object)DBNull.Value : actData.IsoNumber);
cmd.Parameters.AddWithValue("#isActive", actData.IsActive);
cmd.ExecuteNonQuery();
isRecordSaved = true;
}
Everything seems to be fine.
What can possibly be wrong?
Thank you
If you still want to update records when #isoNum is null, then change your procedure to this:
ALTER PROCEDURE [dbo].[SPU_UpdateEmai]
#region char(2),
#isoNum varchar(10),
#isActive bit
AS
BEGIN
SET NOCOUNT ON;
UPDATE MyTable
SET isActive = #isActive, updatedate = GETDATE()
WHERE region = #region
AND (isonumber = #isoNum or #isoNum IS NULL AND isonumber IS NULL)
END

get return value from stored procedure without output parameter

I have a vb.net application that inserts records into a db table using a stored procedure that is supposed to return a value. This stored procedure was setup by someone else and initially was linked to a webservice through which my application made the insert and got the return value in the returned xml. I now have access to the db table and not sure how to receive the return value in my vb.net method.
SQl stored procedure snippet;
#urlname varchar(500),
#siteid varchar(16),
#origin varchar(50),
#queryid varchar(25)
AS
SET NOCOUNT ON;
declare #cnt int
declare #serverip varchar(16)
declare #mincnt int
declare #siteservercnt int
select #cnt=COUNT(*) from sites
where urlname=#urlname
if #cnt = 0
begin
insert into sites (urlname,siteid,exported,origin,queryid)
values(#urlname,#siteid,1,#origin,#queryid)
select #siteservercnt = COUNT(*) from siteserverip where siteid=#siteid
if #siteservercnt=0
begin
select top 1 #mincnt=COUNT(*),#serverip=serverip from siteserverip
group by serverip
order by COUNT(*)
select top 1 #mincnt=sitecount,
#serverip=serverip from serveripcounts
order by sitecount
insert into siteserverip values(#siteid,#serverip)
update serveripcounts set sitecount=sitecount+1
where serverip=#serverip
end
end
SELECT siteid from sites
where urlname=#urlname
return
and my vb.net code to do the insert
CommandObj.CommandText = "Getsite"
CommandObj.CommandTimeout = 90
Dim newUrl As String = String.Empty
CommandObj.Parameters.Clear()
Dim m_param As SqlParameter
m_param = CommandObj.Parameters.Add("#urlname", SqlDbType.VarChar, 500)
m_param.Direction = ParameterDirection.Input
m_param.Value = name
m_param = CommandObj.Parameters.Add("#siteid", SqlDbType.VarChar, 16)
m_param.Direction = ParameterDirection.Input
m_param.Value = siteid
m_param = CommandObj.Parameters.Add("#origin", SqlDbType.VarChar, 50)
m_param.Direction = ParameterDirection.Input
m_param.Value = method
m_param = CommandObj.Parameters.Add("#queryId", SqlDbType.VarChar, 25)
m_param.Direction = ParameterDirection.Input
m_param.Value = forumID
Dim recordsAffected As Integer = CommandObj.ExecuteNonQuery
You can use ExecuteScalar to get that value. ExecuteNonQuery returns number of rows affected while you want to get the value generated by last select. You could use ExecuteReader as well but that is useful when your SP might be returning more columns and/or more rows.
'Populate first column and first row value in siteID
Dim siteID As Integer = CommandObj.ExecuteScalar

execute a stored procedure that returns a " completed succesfully " clue

i have a stored procedure
UPDATE tblTime
SET TimeOut = DATEADD(HOUR,8,TimeIn)
WHERE tId =
(
SELECT MAX(tId)
FROM tblTime
WHERE UserId = 3571
)
although there's no question really, in that case if it did succeed in this query
cause even if the field is empty or if it has value,
it will in this case succeed
but i do need it for future other queries... and also ,
in this case i want the C# code to report
not only that it was requesting query to be execute - meaning it did happen,
but to get an actual answer from sql server
as a return value that c# could use or turn into Boolean
i have managed to do somthing about this so i can specify a condition inside sql server stored proc
declare an OUTPUT variable(PARAMETER) then
set its value to say 1 if condition is met and -1 if not
then
in c# set a function as follows
in this example outpout parameter is named ERROR
public static int UpdateTblViaStoredPRoc(string SPname, int UserID)
{
int message = 0;
using (SqlConnection con = new SqlConnection("server=(local);Initial Catalog=****DBNAME HERE***;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand(SPname, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Uid", UserID);
cmd.Parameters.Add("#ERROR", SqlDbType.Int);
cmd.Parameters["#ERROR"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
message =(int) cmd.Parameters["#ERROR"].Value;
con.Close();
}
return message;
}
stored proc is then allways following the same pattern
declare ERROR parameter, set a condition to output the ERROR accordingly :
ALTER PROCEDURE [dbo].[nameofProc]
#UId Int, #ERROR int OUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TimeOtVal varchar(50)
set #TimeOtVal = (SELECT CASE WHEN [TimeOut] IS NULL THEN '' ELSE CONVERT(NVARCHAR,[TimeOut]) END FROM tblTime WHERE tId = ( SELECT MAX(tId) FROM tblTime WHERE UserId = #UId))
IF (#TimeOtVal = '') -- condition for the update
BEGIN -- now action is taken if condition is met
SET NOCOUNT ON;
UPDATE tblTime SET TimeOut = DATEADD(HOUR,8,TimeIn) WHERE tId = ( SELECT MAX(tId) FROM tblTime WHERE UserId = #UId)
SET #ERROR = 1
END
else
BEGIN -- Other wise , if condition isnot met
SET #ERROR = -1
END
END
so it does what you want only if you allowed it by the condition
then reports the action so you can handle it in program code behind .