If is never working. Always falling in else condition. I have debugged and checked #nextapprover is not null.
IF (#nextApprover != NULL)
BEGIN
UPDATE CallWatching
SET EmployeeNo = #employeeNo
WHERE #SRFID = MasterCode;
INSERT INTO CallForwarding (
MasterCode
,EmployeeNo
,ApproverNo
,IsForwarded
,ForwardBy
)
VALUES (
#SRFID
,#EmployeeNo
,#nextApprover
,0
,#EmployeeNo
)
END
ELSE
BEGIN
UPDATE CallWatching
SET STATUS = 1
WHERE #SRFID = MasterCode;
END
Use IS NOT NULL
i.e. Change: if(#nextApprover!=null)
to IF(#nextApprover IS NOT NULL)
Additionally you should <> instead of != as it is ANSI compliant
Related
is there any way i can use the value of X in the if clause in the else clause
if #bid_value>(SELECT MAX(bid_value) AS X FROM dbo.auctionDetails WHERE status = 0 AND vehicle_id=#vid GROUP BY vehicle_id)
BEGIN
//some code
END
ELSE IF X=NULL
BEGIN
//some code
END
Why don't you create a var for the value?
DECLARE #maxValue INT
SELECT #maxValue = MAX(bid_value)
FROM dbo.auctionDetails
WHERE status = 0 AND vehicle_id = #vid
IF (#bid_value > #maxValue)
BEGIN
// some code
END
ELSE IF (#maxValue IS NULL)
BEGIN
// some code
END
A comment about how you are getting the MAX value: As you are filtering by vehicle_id = #vid, you don't need GROUP BY clause since you will get results for only one value of vahicle_id
You would typically assign the results of the query to a variable.
If you are running SQL Server:
DECLARE #max_bid_value INT;
SELECT #max_bid_value = MAX(bid_value)
FROM dbo.auctionDetails
WHERE status = 0 AND vehicle_id = #vid;
IF #bid_value > #max_bid_value
BEGIN
//some code
END
...
Note that I removed the GROUP BY clause from the original query - I think that this makes it clearer that it should always return a scalar value.
Note that if you want to check if a variable is null, you need #bid is null rather than #bid = null.
Your query should be like below :
DECLARE #X INT
SET #X = (SELECT MAX(bid_value) AS X FROM dbo.auctionDetails WHERE status = 0 AND vehicle_id=#vid);
IF #bid_value>#MAX
BEGIN
//some code
END
ELSE IF X=NULL
BEGIN
//some code
END
I'm new in sql server and I have WHERE clause like this:
WHERE[D].[IsLocked] = 0
AND(#StartDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) >= #StartDate)
AND(#EndDate IS NULL OR ISNULL([TA].[ModifiedDate], [TA].[CreationDate]) <= #EndDate)
AND((CASE WHEN[T].[TaskStatusId] = '09E02513-00AD-49E3-B442-A9ED2833FB25'
THEN 1 ELSE 0 END) = #Completed)
AND((#FilterEmpKey IS NULL AND[TA].[EmpKey] = #CurrentEmpKey)
OR (ISNULL([TA].[ModifiedAssignedBy], [TA].[AssignatedBy]) = #FilterEmpKey
AND[TA].[EmpKey] = #CurrentEmpKey))
But now I want to add if conditional in order to add more filters at the end of query like:
IF(#FilterEmpGuid IS NOT NULL)
AND[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
But I get:
The multi-part identifier [TA].[EmpKey] could not be bound
What am I doing wrong?
IF conditionals are only for use outside sql queries, such as in procedures etc.
In a query itself you are limited to AND, OR and CASE statements, so you will need to rewrite your IF conditional for this:
AND (#FilterEmpGuid IS NULL
OR (
[TA].[EmpKey] = #CurrentEmpKey
AND[TA].[AssignatedBy] = #CurrentEmpKey
AND[TA].[EmpKey] = #FilterEmpKey
))
You could move the additional filter options into a scalar function.
If you know the additional fields that may be filtered, you may be able to get away with something like:
CREATE FUNCTION dbo.ExtendFilter(
#column_value VARCHAR(50), #param_value VARCHAR(50)
)
RETURNS BIT
AS
BEGIN
DECLARE #return BIT = 1; -- default RETURN to 1 ( include ).
IF ( NULLIF( #param_value, '' ) IS NOT NULL )
BEGIN
-- compare the column's value to the param value
IF ( #column_value <> #param_value )
SET #return = 0; -- don't include this record.
END
RETURN #return;
END
GO
And then use it like:
WHERE
{ other WHERE stuff }
AND dbo.ExtendFilter( [TA].[EmpKey], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[AssignatedBy], #CurrentEmpKey ) = 1
AND dbo.ExtendFilter( [TA].[EmpKey], #FilterEmpKey ) = 1
Mind you this is just an example. You'd want to check #pram_value for NULL, etc...
Below I am using OUTPUT Parameters to output an update statement:
UPDATE set Value = src.Value, DeletedDate = iif (#Deleted =1, getutcdate(), NULL), ModifiedBy = SUSER_SNAME(), ModifiedDate = getutcdate()
WHEN NOT MATCHED THEN
INSERT (ConfigKey, Value, AddedBy, ModifiedBy)
VALUES (#ConfigKey, #Value, SUSER_SNAME(), SUSER_SNAME())
OUTPUT 'Core.Config', 'ConfigID', inserted.ConfigID,
iif($action = 'Update', Core.updXMLFragment('Value', inserted.Value, deleted.Value)+
Core.updXMLFragment('ModifiedBy', inserted.ModifiedBy, deleted.ModifiedBy) +
Core.updXMLFragment('DeletedDate', inserted.DeletedDate, deleted.DeletedDate)
, Core.insXMLFragment('ConfigID') +
Core.addnlXMLFragment ('ModifiedBy', inserted.ModifiedBy))
The code above generates the update statement at the bottom, but the issue I have is 'DeletedDate = 0' in the update statement. I need this to be changed to DeletedDate=NULL and in the condition 'DeletedDate IS NULL'. How can this be done?
BEGIN TRAN
update Core.Config
set Value = 'Insert',ModifiedBy = 'HARROGATE\Name' ,DeletedDate = '0'
where ConfigID = '1' and Value = 'Update' and ModifiedBy = 'HARROGATE\Name' and DeletedDate = '0'
if ##ROWCOUNT <> 1
BEGIN;
THROW 99999, 'Error - Single Row not updated, rollback terminated', 1;
END;
UPDATE: Included updxmlfragment
BEGIN
if (#InsertedValue = '')
BEGIN
set #InsertedValue = ' '
END
if(#DeletedValue = '')
BEGIN
set #DeletedValue = ' '
END
if(#FieldName IS NULL)
--if(#InsertedValue IS NULL and #DeletedValue IS NULL or #FieldName IS NULL) -- pre v2.1 logic
BEGIN
-- This "errors" the function and ensures the script doesn't get any further than the update
return convert(int, 'NULL Params passed for XML Fragment Generation')
END
-- Validate the date has the correct "time" element associated - i.e HH:MM:SS:MSS
if (#FieldName like '%date%')
BEGIN
if((TRY_PARSE(#InsertedValue as datetime) IS NOT NULL) or (TRY_PARSE(#DeletedValue as datetime) IS NOT NULL))
BEGIN
if((len(replace(#DeletedValue, ':', '')) +3 <> len(#deletedvalue)) OR (len(replace(#InsertedValue, ':', '')) +3 <> len(#InsertedValue)))
BEGIN
-- This "errors" the function and ensures the script doesn't get any further than the update
return convert(datetime, 'Invalid Date Params passed for XML Fragment Generation')
END
END
END
return
'<Update><FieldName>'+#FieldName+'</FieldName>'+iif(#DeletedValue is null, '<OldValue />', '<OldValue><![CDATA['+#DeletedValue+']]></OldValue>')
+iif(#InsertedValue is null, '<NewValue />', '<NewValue><![CDATA['+#InsertedValue+']]></NewValue>') + '</Update>
'
Why not to use NULLIF()?
Returns a null value if the two specified expressions are equal.
So you'd have to use NULLIF(DeletedDate, 0) instead of DeletedDate only.
Update
As per my understanding, you have to use it like that:
UPDATE
SET Value = src.Value
, DeletedDate = IIF(#Deleted = 1, getutcdate(), NULL)
, ModifiedBy = SUSER_SNAME()
, ModifiedDate = getutcdate() WHEN NOT MATCHED THEN
INSERT (ConfigKey, Value, AddedBy, ModifiedBy)
VALUES (#ConfigKey, #Value, SUSER_SNAME(), SUSER_SNAME())
OUTPUT 'Core.Config'
, 'ConfigID'
, inserted.ConfigID
, IIF($ACTION = 'Update', Core.updXMLFragment('Value', inserted.Value, deleted.Value) + Core.updXMLFragment('ModifiedBy', inserted.ModifiedBy, deleted.ModifiedBy) + Core.updXMLFragment('DeletedDate', NULLIF(inserted.DeletedDate, 0), NULLIF(deleted.DeletedDate, 0))
, Core.insXMLFragment('ConfigID') + Core.addnlXMLFragment('ModifiedBy', inserted.ModifiedBy))
UPDATE Core.Config
SET Value = 'Insert'
, ModifiedBy = 'HARROGATE\Name'
, DeletedDate = NULL
WHERE ConfigID = '1'
AND Value = 'Update'
AND ModifiedBy = 'HARROGATE\Name'
AND NULLIF(DeletedDate, 0) IS NULL;
IF( #ActiveStatus = 1 )
BEGIN
#PasswordStatus = 3
END
ELSE
SET #PasswordStatus = (SELECT password_status
FROM tbl_user
WHERE login_name = #LoginName_fromApp
AND password=#Pass
)
I am using Microsoft SQL Server Management Studio..
yes
In IF clause you need to set variable so use select or set, do not write directly #PasswordStatus = 3 write set/select #PasswordStatus = 3
try
if( #ActiveStatus = 1 )
begin
--chage of code
set #PasswordStatus = 3 --or select #PasswordStatus = 3
END
else
begin
Set #PasswordStatus = (select password_status from tbl_user where login_name=#LoginName_fromApp and password=#Pass)
end
EDIT
Comment of -# marc_s Use SET #Var = 3 if you're just setting a "scalar" value - use SELECT #Var = ID FROM dbo.Table1 if you're actually selecting from a table (or view)
when you r setting valuer to any variable use Set as followed
if( #ActiveStatus = 1 )
begin
Set #PasswordStatus = 3
END
else
begin
Set #PasswordStatus = (select password_status from tbl_user where
login_name=#LoginName_fromApp and password=#Pass)
end
Select #PasswordStatus
Another one
select
#PasswordStatus = case when #ActiveStatus = 1 then 3 else password_status end
from
tbl_user
where
login_name = #LoginName_fromApp and password=#Pass
I'm very new to FireBird, but I want to know how I can use a select statement as part of my conditional criteria. I feel like I've been to the internet in back trying to find a way to do this, but haven't come up with much. Below is my attempt at getting this to work. Thanks in advance for any help.
SET TERM ^ ;
ALTER PROCEDURE sp_test (
IPADD Varchar(32),
HN Varchar(32),
NOTE Varchar(200) )
RETURNS ( update_count integer )
AS
BEGIN
IF((SELECT COUNT(*)
FROM ADDRESSES a
WHERE a.ADDRESS_TYPE = 'Reserved'
AND a.ALIVE = 'N'
AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL)
AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL)
AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)) > 0)
THEN
UPDATE
ADDRESSES a
SET
a.HOST_NAME = :HN,
a.ADDRESS_TYPE = 'Assigned',
a.NOTES = :NOTE
WHERE
a.SHORT_IP_ADDRESS = :IPADD;
update_count = 1;
SUSPEND;
ELSE
update_count = 0;
SUSPEND;
END^
SET TERM ; ^
GRANT EXECUTE
ON PROCEDURE sp_test TO SYSDBA;
Using COUNT to check is there records to update is not the best way, use EXISTS instead, ie your IF would be
IF(EXISTS(SELECT 1 FROM ADDRESSES a
WHERE a.ADDRESS_TYPE = 'Reserved'
AND a.ALIVE = 'N'
AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL)
AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL)
AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)))
THEN
But there seems to be a problem with your return value, update_count - you return 1 if you execute the UPDATE, but the actual number of rows affected by the statement might be something else. I suggest you use ROW_COUNT context variable instead. So your procedure would be
ALTER PROCEDURE sp_test (
IPADD Varchar(32),
HN Varchar(32),
NOTE Varchar(200) )
RETURNS ( update_count integer )
AS
BEGIN
IF(EXISTS(SELECT 1 FROM ADDRESSES a
WHERE (a.ADDRESS_TYPE = 'Reserved')
AND (a.ALIVE = 'N')
AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL)
AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL)
AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)))
THEN BEGIN
UPDATE ADDRESSES a SET
a.HOST_NAME = :HN,
a.ADDRESS_TYPE = 'Assigned',
a.NOTES = :NOTE
WHERE a.SHORT_IP_ADDRESS = :IPADD;
update_count = ROW_COUNT;
END ELSE update_count = 0;
SUSPEND;
END^