Adding with NULL in SQL - sql

i'm planning to add sql values.
Dim cmdStringc23 As String = " Update [Associate_wise_chart]
set [Hours]= (select SUM(tat) from [Dashboard].[dbo].[Dashboard]
where [assignee] like '%Santosh%') + (select SUM(tat)
from [Dashboard].[dbo].[requests]
where [assignee] like '%Santosh%') "
So consider,
value from dashboard table is 10
value from requests table is NULL.
So I'm getting answer as 10+NULL = NULL.
I have set tat as NULL. My requirement , i have to display answer as 10 and not as NULL
Could any one have a look ?

Use ISNULL function from SQL ...
Update [Associate_wise_chart]
set [Hours]= ISNULL((select SUM(tat) from [Dashboard].[dbo].[Dashboard]
where [assignee] like '%Santosh%'), 0) + ISNULL((select SUM(tat)
from [Dashboard].[dbo].[requests]
where [assignee] like '%Santosh%'), 0) "
That will get you ISNULL(10, 0) + ISNULL(NULL, 0) = 10 + 0 = 10

You can't.
NULL is a synonym for "unknown". Ten plus unknown is unknown. The unknown can be 0, -1, 42, or even 6E23+π/2. But it's still unknown.
This is why you get NULL.
Instead, check for NULLs, and only add the other value, if it is not NULL.

set NOTNULL while creating the table

fast and easy just convert tat column into Not Null and have 0 in place of NULL.

Dim cmdStringc23 As String = " Update [Associate_wise_chart]
set [Hours]= (select isnull(sum(tat), 0) from [Dashboard].[dbo].[Dashboard]
where [assignee] like '%Santosh%') + (select isnull(sum(tat), 0)
from [Dashboard].[dbo].[requests]
where [assignee] like '%Santosh%') "
Use isnull

Update [Dashboard].[dbo].[Associate_wise_chart]
set [Hours]= ISNULL ( (select SUM(tat) from [Dashboard].[dbo].[Dashboard] where [assignee] like '%Santosh%'),0) + ISNULL((select SUM(tat) from [Dashboard].[dbo].Unbuilds where [assignee] like '%Santosh%'),0) where [Name]='Santhosh'
ISNULL is working. Thank you Everyone.

Related

Update multiple values using IS NULL condition

I just finished migrating an Access database to the SQL Server and I need to fix the Yes/No values to be defaulted to No as their data type conversion is set to bit.
I do this by setting the default value to 0.
However, I want to execute a query to do that as well, but there are multiple bit rows.
I know how to use multiples with the SET command, but how do we use multiple with WHERE? What is the proper way of structuring it?
UPDATE sometable SET
[isConditionOnePassed] = 0
, [isSecondPassed] = 0
, [isThirdPassed] = 0
WHERE [isConditionOnePassed] IS NULL, [isSecondPassed] is NULL, [isThirdPassed] IS NULL
Or is it with an AND? Like boolean logic?
UPDATE sometable SET
[isConditionOnePassed] = 0
, [isSecondPassed] = 0
, [isThirdPassed] = 0
WHERE [isConditionOnePassed] IS NULL and [isSecondPassed] is NULL and [isThirdPassed] IS NULL
Hmmm . . . If you want to set NULL values to another value, you can use COALESCE():
UPDATE sometable
SET isConditionOnePassed = COALESCE(isConditionOnePassed, 0),
isSecondPassed = COALESCE(isSecondPassed, 0),
isThirdPassed = COALESDCE(isThirdPassed, 0)
WHERE isConditionOnePassed IS NULL OR isSecondPassed is NULL OR isThirdPassed IS NULL;
Seems like what you really need is an ISNULL or CASE expression. Here is an example with both:
UPDATE dbo.SomeTable
SET isConditionOnePassed = ISNULL(isConditionOnePassed,0),
isSecondPassed = CASE isSecondPassed WHEN 1 THEN 1 ELSE 0 END;

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)

How to set optional parameter for int type variable

Have two variable StatusTypeTestID and StatusTestID want to set them as optional in where clause as like bellow,but optional option not work for int variable.
Note: default value for int variable is 0
DECLARE #StatusTypeTestID as int
SET #StatusTypeTestID = 1
DECLARE #StatusTestID as int
SET #StatusTestID = 0
select *
from LiveCustomerStatus
where (StatusType=#StatusTypeTestID
and (Status = #StatusTestID or #StatusTestID is null))
As you were already trying, you can check if your parameters have been set as null or if they match the correspondent field.
This way you can leave a parameter as null if you want it to be optional, not affecting the result.
select *
from LiveCustomerStatus
where (#StatusTypeTestID is null or StatusType=#StatusTypeTestID)
and (#StatusTestID is null or Status = #StatusTestID)
option(recompile)
I have added a option(recompile) clause that will force SQL Server to recompile the query at every execution. This way it will use the appropriate indexes to optimize it depending of the value of the parameters (wether they are null or not).
You can comment both set statements and below query will work:
select * from LiveCustomerStatus
where (#StatusTypeTestID is null or StatusType=#StatusTypeTestID)
and (#StatusTestID is null or Status = #StatusTestID)
Use CASE Statement in WHERE clause :
SELECT *
FROM LiveCustomerStatus
WHERE StatusType = CASE WHEN ISNULL(#StatusTypeTestID,'') = '' THEN
StatusType ELSE #StatusTypeTestID END
AND Status = CASE WHEN ISNULL(#StatusTestID,'')= '' THEN Status ELSE
#StatusTestID END

WHERE [Expression] = TRUE/FALSE in SQL Server

I have a situation where I'm trying to filter people that have credits or not. Here's an example Dapper query for reference:
var sql = #"
SELECT *
FROM Person
WHERE (Person.Credits > 0) = #hasCredits";
Connection.Query(sql, new { hasCredits });
I was pretty sure Postgres allows you to do this, hence my surprise when on SQL Server this failed with Incorrect syntax near '='.
With the sample data below, I would expect the query to return the Person with the ID of 1 when hasCredits is FALSE and the Person with the ID of 2 when hasCredits is TRUE.
INSERT INTO Person (PersonId, Credits) VALUES (1, 0), (2, 0);
In SQL Server Is there a way to evaluate whether an expression evaluates to true or false?
I've considered the following (horrible looking) options, but was hoping there was a more elegant solution:
"WHERE (Person.Credits " + (hasCredits ? ">" : "=") + " 0)"
"WHERE (#hasCredits = 1 AND Person.Credits > 0) OR (#hasCredits = 0 AND Person.Credits = 0)"
Considering that when Has credits radio button is selected #hasCredits variable will have 1 else when Doesn't have credits is selected #hasCredits variable will have 0 else #hasCredits variable will be null
SELECT *
FROM Person
WHERE (Person.Credits > 0 and #hasCredits=1) or --Has credits
(Person.Credits <1 and #hasCredits=0) or --Doesn't have credits
(#hasCredits IS NULL) --Don't care
You question was quite plain and the answer is super easy!
case when Person.Credit > 0 then 1 else 0 end = #hasCredits

Nhibernate Criteria Conditional Where

Im working on a NHibernate criteria wich i graduatly builds upp depending on input parameters.
I got some problem with the postal section of these paramters.
Since we got a 5 number digit zipcodes the input parameter is a int, but since we in database also accept foreign zipcodes the database saves it as string.
What im trying to replicate in NHibernate Criteria/Criterion is the following where clause.
WHERE
11182 <=
(case when this_.SendInformation = 0 AND dbo.IsInteger(this_.Zipcode) = 1 then
CAST(REPLACE(this_.Zipcode, ' ', '') AS int)
when this_.SendInformation = 1 AND dbo.IsInteger(this_.WorkZipcode) = 1 then
CAST(REPLACE(this_.WorkZipcode, ' ', '') AS int)
when this_.SendInformation = 2 AND dbo.IsInteger(this_.InvoiceZipcode) = 1 then
CAST(REPLACE(this_.InvoiceZipcode, ' ', '') AS int)
else
NULL
end)
What we do is to check where the member contact (this_) has preferenced to get information sent to, then we check the input zipcode as integer against three different columns depending on if the column is convertable to int (IsInteger(expr) function) if column is not convertable we mark the side as NULL
in this case we just check if the zipcode is >= input parameter (reversed in sql code since paramter is first), the goal is to do a between (2 clauses wrapped with 'AND' statement), >= or <=.
UPDATE
Got a hint of success.
Projections.SqlProjection("(CASE when SendInformation = 0 AND dbo.IsInteger(Zipcode) = 1 then CAST(REPLACE(Zipcode, ' ', '') AS int) when SendInformation = 1 AND dbo.IsInteger(WorkZipcode) = 1 then CAST(REPLACE(WorkZipcode, ' ', '') AS int) when SendInformation = 2 AND dbo.IsInteger(InvoiceZipcode) = 1 then CAST(REPLACE(InvoiceZipcode, ' ', '') AS int) else NULL END)"
, new[] { "SendInformation", "Zipcode", "WorkZipcode", "InvoiceZipcode" },
new[] { NHibernateUtil.Int32, NHibernateUtil.String, NHibernateUtil.String, NHibernateUtil.String });
Throw my whole clause in a Projections.SqlProjection, however when i run my code some of my projection is cut (" AS int) else NULL END)" is cut from the end) and makes the sql corrupt.
Is there some kind of limit on this ?
Got it working yesterday.
Projections.SqlProjection worked, however if you don't name the projection as a column it some how cuts some of the TSQL code.
(Case
when x = 1 then 'bla'
when x = 2 then 'bla_bla'
else NULL
END) as foo
when using the last part (as foo) and naming the entire case syntax it works and dont cut anything.
However i dont know why but i could not manage to use the aliases from the other part of the criteria.