Variable is getting NULL after SUM function in SQL Server - sql

I have this code that is part of a stored procedure:
SET #_Value = 0
SET #_Cont = 1;
IF(#_FlagControl = 1)
BEGIN
SELECT #_Value = SUM(Value)
FROM Person P
INNER JOIN Order O on O.CodPerson = P.CodOrder
WHERE P.CodPerson = #_CodP
AND P.CodImp <> 3
AND P.FlagSituation = 1
AND #_CodMainPerson = P.CodPerson
IF(#_Value IS NULL)
PRINT 'NULL'
ELSE
PRINT #_Value
END
If I run just this SELECT inside the "IF", it returns '0.90'. But when I run this entire query inside a procedure, it is printing NULL.
I don't have idea what is going on.

You assign #_Value
You check #_Value
You print #_ValorImposto
So if #_Value is not null, you don't print it...
Edit, it is not this
Therefore, the SELECT has no rows, which when SUMMed gives one row, making #_Value NULL
So test and fix the SELECT in the stored procedue: print #_CodP and #_CodMainPerson. SELECT without the SUM.
Not in another query with hardcoded values: this proves nothing
Note that SUM without GROUP BY always returns exactly one row.
So #_Value will always either either a non-null value or NULL
See Does COUNT(*) always return a result? for more

Related

Using SELECT subquery in a CASE statement and handling NULLS

I have 2 SQL tables one holding stock information then a style table which details how the stock is used. For some jobs the information is contained with a print file so the value in the stock table would be BIN, if not it would contain a template name which would cause a query to a Styles table which then shows how the stock is used. There a 10 positions that a stock could be applied but the template table wouldn't have records for where a stock couldn't be used (on the back of a simplex job for example).
I have a stored procedure which works to provide the detail based on whether the logic value is BIN or not but for the records in the style table that have no value I get NULL back which I need to suppress but just putting ISNULL around the column name in the subquery isn't having any effect. Am I just missing something as I'd rather not nest in another CASE statement to check if the query would produce NULL
WITH STYLES AS
(
SELECT
#JOBNAME AS JobName, Logic AS StyleName
FROM
[dbo].[CON_Tbl_511_DigitalStocks]
WHERE
JOBNAME = #JOBNAME
)
SELECT TOP 1
[Logic],
[S1F], [S1B], [S2F], [S2B],
[S3F], [S3B], [S4F], [S4B],
[S5F], [S5B],
CASE
WHEN b.stylename = 'BIN'
THEN --checks if there is a style for this job
CASE
WHEN S1F = '' THEN ''
ELSE '1'
END -- if a stock code is specified then return the bin name ("1")
ELSE (SELECT PAGE
FROM [dbo].[CON_Tbl_512_DigitalLogic]
WHERE STYLENAME = B.StyleName
AND STOCKREF = 'S1F')
END AS S1F_LOGIC, -- If a style is used return the style instruction for this bin and side
CASE
WHEN b.stylename = 'BIN' -- repeat this for all bins/sides
THEN
CASE WHEN S1B = '' THEN ''
ELSE '1'
END
ELSE (SELECT PAGE
FROM [dbo].[CON_Tbl_512_DigitalLogic]
WHERE STYLENAME = B.StyleName AND STOCKREF = 'S1B')
END AS S1B_LOGIC,
CASE WHEN b.stylename = 'BIN' THEN
CASE WHEN S2F = '' THEN ''
ELSE '2' END
ELSE (SELECT PAGE FROM [dbo].[CON_Tbl_512_DigitalLogic] WHERE STYLENAME = B.StyleName AND STOCKREF = 'S2F') END AS S2F_LOGIC -- this one returns NULL as there is no instruction required for "2SF"
FROM
[CON_Tbl_511_DigitalStocks] A
JOIN
STYLES B ON A.JOBNAME = B.JOBNAME
WHERE
A.JobName = #JobName
This code works fine until the last one as there is no value in the stockref column that says 'S2F' but putting SELECT ISNULL(PAGE, '') still returns NULL
Because this query is not finding any records:
SELECT PAGE FROM [dbo].[CON_Tbl_512_DigitalLogic] WHERE STYLENAME = B.StyleName AND STOCKREF = 'S2F'
and you want it to return something, you can change it to:
SELECT coalesce(min(PAGE),'') FROM [dbo].[CON_Tbl_512_DigitalLogic] WHERE STYLENAME = B.StyleName AND STOCKREF = 'S2F'
This will return the minimum value (min) of the found records, which will return NULL when noting found. The coalesce will turn this NULL into the empty string: ''
P.S.: see also SQL - Difference between COALESCE and ISNULL?

SELECT WHERE {column} = CASE WHEN {expression} THEN NULL

I have this code which is part of a stored procedure
INSERT INTO #TempTable
/* A few subqueries, about 100 lines */
WHERE (cartera.ClaSucursal = #pIdSucursal OR #pIdSucursal = -1)
AND (cartera.ClaAsesorActual =
CASE
WHEN #pIdAsesor > 0 THEN #pIdAsesor
WHEN #pIdAsesor = 0 THEN NULL
END
OR #pIdAsesor = -1)
/* Rest of my code, about 200 lines */
SELECT * FROM #TempTable
Basically I have a parameter called #pIdAsesor and depending on its value there can be three possible outcomes.
#pIdAsesor = -1 which brings me all entries regardless of the Id value
#pIdAsesor = sumId which brings me all entries with given Id
#pIdAsesor = 0 which brings me all entries with NULL as the Id
Outcomes 1 and 2 work flawlessly, but scenario 3 doesn't bring back results.
null isn't a value - it's the lack thereof. null is never equal to anything (not even another null), but you can check for it explicitly with the is operator.
You could ditch the case expression and construct this logic with a series of ors:
AND ((#pIdAsesor = -1) OR
(#PIdAsesor = 0 AND cartera.ClaAsesorActual IS NULL) OR
(#pIdAsesor = cartera.ClaAsesorActual))
You can't use = for null in case when result comes null but = null doesn't work. You have to use is null.

SQL : Update value when the value in the database is null

I know this is already asked question and possible to be close.
But i really want a answer, I already searched through the internet, Read documentations, Blogs, and Question to SO.
This is my Query so Far,
declare #count numeric
select #count = (select count(1) from E496_TitleReference a where
exists (select 1 from #tempTransactions b where a.EPEB_RoD = b.tEPEB_RoD and
a.EPEB_ENO = b.tEPEB_ENO and a.EPEB_ID = b.tEPEB_ID and a.Title_Seq = b.tTitle_Seq))
update E496_TitleReference
set PrintStatus = '{0}',Is_AESM=isnull(-1,Is_AESM)
from E496_TitleReference a where
exists (select 1 from #tempTransactions b where a.EPEB_RoD = b.tEPEB_RoD and
a.EPEB_ENO = b.tEPEB_ENO and a.EPEB_ID = b.tEPEB_ID and a.Title_Seq = b.tTitle_Seq)
if ##rowcount <> #count
begin
rollback tran
Print "Error: There is an error on table E496_TitleReference."
return
end
go
For eg, In my table in Database i have column name Is_AESM, In Is_AESM column it have 4 values.
Is_AESM
NULL
NULL
-1
-2
Something like this.
Now when i run my script, it has no problem when i run it,
Is_AESM=isnull(-1,Is_AESM)
In this query it will detect if Is_AESM is null, it will update Is_AESM = -1 if not it will retain the value.
Now my problem is, if my query detect Is_AESM has a null value, it will update all the value to -1.
Is_AESM
-1
-1
-1
-1
The result is something like that. Now i want is update only the null value not all the value in column Is_AESM.
I think this query is wrong Is_AESM=isnull(-1,Is_AESM).
Any ideas will be a big help.
You may try with coalsece() function
update E496_TitleReference
set PrintStatus = '{0}',Is_AESM=coalsece(Is_AESM,-1)
from E496_TitleReference a where
exists (select 1 from #tempTransactions b where a.EPEB_RoD = b.tEPEB_RoD and
a.EPEB_ENO = b.tEPEB_ENO and a.EPEB_ID = b.tEPEB_ID and a.Title_Seq = b.tTitle_Seq)
you need to replace order of parameters.
Is_AESM=isnull(Is_AESM, -1)
You can use COALSECE function. It returns the first non-null entry from the given list. So:
Is_AESM= COALSECE(IS_AESM,-1)
This will return IS_AESM value if it is not null (since it is the first non-null value)
Else if IS_AESM is NULL then it returns -1 (since it is the non-null value)

Multiple or condition in sql store procedure

I am trying to check multiple OR conditions inside if block but its my code inside if block still gets executed even if GUIDStatement is 'ContactDetailsGUID' or 'FILECONTENTSGUID' or 'AccountGUID'.
I have a cursor which keeps assigning single value to GuidStatement variable. So at any given point of time my #GUIDStatements variable will have any single name
My If condition should not get executed when my GUIDStatement has any of the above value
My if condition is as follows. Please help.
IF ( (#GUIDStatements <> 'ContactDetailsGUID') OR (#GUIDStatements <> 'FILECONTENTSGUID') OR (#GUIDStatements <> 'AccountGUID'))
Run the code below. The first block of code, your code, returns false regardless of the value of #GUIDStatements. The second block, suggestion, returns false if #GUIDStatements is in one of the three values and true otherwise. I think, as I understand your question, thatis what you're looking for. If not please comment and I'll try to clarify.
DECLARE #GUIDStatements SYSNAME = N'not';
--
-- your code
-------------------------------------------------
IF (
(
#GUIDStatements <> 'ContactDetailsGUID'
)
OR
(
#GUIDStatements <> 'FILECONTENTSGUID'
)
OR
(
#GUIDStatements <> 'AccountGUID'
)
)
SELECT N'false'
ELSE
SELECT N'true';
--
-- suggestion
-------------------------------------------------
IF #GUIDStatements IN ( 'ContactDetailsGUID', 'FILECONTENTSGUID', 'AccountGUID' )
SELECT N'false'
ELSE
SELECT N'true';
How about:
IF #GUIDStatements NOT IN ('ContactDetailsGUID', 'FILECONTENTSGUID', 'AccountGUID')
Easier to maintain too.

conditional handling of update sql script depending on input parameter

I am new to SQL and using Oracle 11. I need to write a sql script which uses different update command based on whether the input param is null or not null.
I need something like this
['&' followed by the parameter name is the way i see parameters being used in other such
script for our project]
IF &PRG_ID IS NULL
UPDATE PROGRAM_TABLE P SET HANDLED_IND = 'Y' WHERE EXISTS
(SELECT 1 FROM HANDLED_PROGRAM H WHERE H.PROGRAM_ID = P.PROGRAM_ID);
ELSE
UPDATE PROGRAM_TABLE P SET HANDLED_IND = 'Y' WHERE
P.PROGRAM_ID = &PRG_ID AND EXISTS
(SELECT 1 FROM HANDLED_PROGRAM H WHERE H.PROGRAM_ID = P.PROGRAM_ID);
END IF;
Something like (is not tested):
UPDATE PROGRAM_TABLE P SET HANDLED_IND = 'Y' WHERE EXISTS
(SELECT 1 FROM HANDLED_PROGRAM H WHERE H.PROGRAM_ID = P.PROGRAM_ID)
AND (&PRG_ID IS NULL OR P.PROGRAM_ID = &PRG_ID);
But take into account this change may lead to the performance degradation for the case when PRG_ID has definite value.