Alternative to Scalar Function in MS SQL - sql-server

Instead of below query what I can use to convert sql data to json object.
CREATE FUNCTION [dbo].[ES_GetSchools](#IdListing NVARCHAR(400))
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN(
SELECT
CASE WHEN ISNULL(SchoolDistrictId,'')<>'' THEN
SUBSTRING(SchoolDistrictId,1,CHARINDEX(':',SchoolDistrictId)-1)ELSE NULL END AS 'district.name',
CASE WHEN ISNULL(SchoolDistrictId,'')<>'' THEN
SUBSTRING(SchoolDistrictId,CHARINDEX(':',SchoolDistrictId)+1,LEN(SchoolDistrictId))ELSE NULL END AS 'district.id',
CASE WHEN ISNULL(SchoolDistrictSEOPath,'')<>'' AND SchoolDistrictSEOPath<>'0' THEN
SchoolDistrictSEOPath ELSE NULL end 'district.seo',
CASE WHEN ISNULL(SchoolElementary,'')<>'' THEN
CASE WHEN CHARINDEX(':',SchoolElementary)>0 THEN
SUBSTRING(SchoolElementary,1,CHARINDEX(':',SchoolElementary)-1) ELSE SchoolElementary END ELSE NULL END AS 'elementary.name',
CASE WHEN ISNULL(SchoolElementary,'')<>'' THEN
CASE WHEN CHARINDEX(':',SchoolElementary)>0 THEN
SUBSTRING(SchoolElementary,CHARINDEX(':',SchoolElementary)+1,LEN(SchoolElementary)) ELSE NULL END ELSE NULL END AS 'elementary.id',
CASE WHEN ISNULL(SchoolHigh,'')<>'' THEN
CASE WHEN CHARINDEX(':',SchoolHigh)>0 THEN
SUBSTRING(SchoolHigh,1,CHARINDEX(':',SchoolHigh)-1)ELSE SchoolHigh END ELSE NULL END AS 'high.name',
CASE WHEN ISNULL(SchoolHigh,'')<>'' THEN
CASE WHEN CHARINDEX(':',SchoolHigh)>0 THEN
SUBSTRING(SchoolHigh,CHARINDEX(':',SchoolHigh)+1,len(SchoolHigh))ELSE NULL END ELSE NULL END AS 'high.id',
CASE WHEN ISNULL(SchoolMiddle,'')<>'' THEN
CASE WHEN CHARINDEX(':',SchoolMiddle)>0 THEN
SUBSTRING(SchoolMiddle,1,CHARINDEX(':',SchoolMiddle)-1)ELSE SchoolMiddle END ELSE NULL END AS 'middle.name',
CASE WHEN ISNULL(SchoolMiddle,'')<>'' THEN
CASE WHEN CHARINDEX(':',SchoolMiddle)>0 THEN
SUBSTRING(SchoolMiddle,CHARINDEX(':',SchoolMiddle)+1,len(SchoolMiddle))ELSE NULL END ELSE NULL END AS 'middle.id'
FROM Table_Name1 a WITH (NOLOCK)
WHERE a.IdListing = #IdListing
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER
)
END
GO
SELECT dbo.[ES_GetSchools](Idlisting) from Table_Name1 a join Table_Name2 b on a.idlisting=b.idlisting

Use the following syntax
SELECT field1, field2
FROM table
FOR JSON AUTO

Related

How to use a query-results in the same Select statement?

In my select statement I calculate some values and then need to calculate a new value based on the results of the already calculated values. How can this be archived without using a temp table?
SELECT
CASE WHEN [Customer] = '173220000' THEN '1' ELSE NULL END AS Ver_a
, CASE WHEN [Service] = '173220000' THEN '1' ELSE NULL END AS Ver_b
, CASE WHEN [Productavailability] = '173220000' THEN '1' ELSE NULL END AS Ver_c
, (SUM(Ver_a, Ver_b, Ver_c)/3) AS Identity_Ver
FROM x
Just use a sub-query/derived table:
SELECT
Ver_a
, Ver_b
, Ver_c
, (coalesce(Ver_a,0) + coalesce(Ver_b,0) + coalesce(Ver_c,0))/3 AS Identity_Ver
FROM (
SELECT
CASE WHEN [Customer] = '173220000' THEN '1' ELSE NULL END AS Ver_a
, CASE WHEN [Service] = '173220000' THEN '1' ELSE NULL END AS Ver_b
, CASE WHEN [Productavailability] = '173220000' THEN '1' ELSE NULL END AS Ver_c
FROM x
) x
Note 1: as you are not grouping you don't need the sum function, just the sum operator (+) - and the sum function doesn't take a comma separated list of values either.
Note 2: your sum won't work without using the coalesce function as you are returning null from the case expressions.
Firstly, you cannot do sum(var1, var2, var3).
The answer to your question, as stated, seems to be the code at the end.
BUT, I have to ask: what do you want to accomplish? Your approach does make sense to me :-(
SELECT
Sum(
CASE WHEN [customer] = '173220000' THEN 1 ELSE 0 END +
CASE WHEN [service] = '173220000' THEN 1 ELSE 0 END +
CASE WHEN [productavailability] = '173220000' THEN 1 ELSE 0 END
) / 3 AS Identity_Ver
FROM x

SQL - Alias in CASE statements

I have this piece of code (please look below). I keep getting error: "Invalid column name 'SuppFinish2'
SELECT
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2],
CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST]
FROM TABLE
Is it because of [SuppFinish2] being an alias? Thanks!
As you said its due to alias and aliased columns can be referenced only on order by to logical query flow order
with cte
as
(
SELECT
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2]
FROM TABLE
)
select
CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST]
from cte
You cant use those aliases in the same level as you created them, becuase they are not existing yet.. wrap your query with another select like this:
SELECT * ,
CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST]
FROM (
SELECT
[ID],
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2],
FROM TABLE)
In order to reference aliased columns, you can use a derived table (or CTE, but that is not shown here)
Select *, CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST] From
(
SELECT
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2]
) T1
FROM TABLE
You cannot, at the same time, set and access an alias in the SELECT clause. I would suggest rewriting your query using CROSS APPLY:
SELECT t1.[RegFinish],
t2.[SuppFinish],
CASE
WHEN t1.[RegFinish] < t2.[SuppFinish] THEN '1'
ELSE '0'
END AS [TEST]
FROM TABLE
CROSS APPLY (SELECT COALESCE([RegFinish], '') AS [RegFinish]) AS t1
CROSS APPLY (SELECT COALESCE([SuppFinish], '') AS [SuppFinish]) AS t2
SELECT ISNULL([RegFinish],'') as [RegFinish]
, ISNULL([SuppFinish],'') as [SuppFinish2], CASE
WHEN
ISNULL([RegFinish],'') < ISNULL([SuppFinish],'') THEN 1
ELSE 0
END AS [TEST]
FROM TABLE
Why not use ISNULL instead of CASE? The problem with your query is that [SuppFinish2] is an alias not an column and can only be used in ORDER BY clause

T-SQL - Assign field to NULL in a case statement

Probably am going crazy, but I am trying to assign a field to NULL in a case statement, however, I get an error on the equals next to the NULL keyword
Here is the SQL:
SELECT CASE WHEN enq.IntField = 0 THEN enq.IntField = NULL ELSE enq.IntField END As IntField
FROM [Table]
Surely I am doing something stupid!!
Thanks in advance
Try this
CASE WHEN enq.IntField = 0 THEN NULL ELSE enq.IntField END

How to check for NULL in a CASE statement with a Scalar Function?

How do you check for NULL in a CASE statement, when you're using a Scalar Function?
My original query was ... but it fails
SELECT CASE dbo.fnCarerResponse('')
WHEN NULL THEN 'Pass'
ELSE 'Fail'
END
I read the SO question about using IS NULL, like so ...
SELECT CASE dbo.fnCarerResponse('') IS NULL
WHEN NULL THEN 'Pass'
ELSE 'Fail'
END
but this gives the incorrect syntax near the keyword is error
Can you have a Scalar Function in the CASE ?
You are using the wrong style of CASE - you need to use CASE WHEN <expression> THEN not CASE <expression> WHEN <expression> then:
SELECT CASE
WHEN dbo.fnCarerResponse('') IS NULL
THEN 'Pass'
ELSE 'Fail'
END
SELECT CASE
WHEN dbo.fnCarerResponse('') IS NULL
THEN 'Pass'
ELSE 'Fail'
END
SELECT CASE
WHEN dbo.fnCarerResponse('') is NULL THEN 'Pass'
ELSE 'Fail'
END
You can use this way too:
SELECT CASE ISNULL(dbo.fnCarerResponse(''),'NULLVALUE')
WHEN 'NULLVALUE' THEN 'Pass'
ELSE 'Fail'
END
When used in the context of a list, such as the definitions of the columns of a SELECT query, the entire expression must be wrapped in parentheses, like this.
,LastEditorEmail = (SELECT CASE
WHEN CF.LastModifiedBy IS NULL THEN
NULL
ELSE
UE.Email
END)

determine if any values are null, if true then false, else true

I currently have a select statement that checks several columns to see if they have data. if any of them are null then i want a bit set to false. if none of them are null then i want a bit set to true. here's what i currently have:
select
cast(
case when ChangeOrderNumber is null then 0 else 1 end *
case when ClientName is null then 0 else 1 end *
case when QuoteNumber is null then 0 else 1 end *
case when ClientNumber is null then 0 else 1 end *
case when ServiceLine is null then 0 else 1 end *
case when ServiceLineCode is null then 0 else 1 end *
case when GroupLeader is null then 0 else 1 end *
case when CreatedBy is null then 0 else 1 end *
case when PTWCompletionDate is null then 0 else 1 end *
case when BudgetedHours is null then 0 else 1 end *
case when BudgetDollars is null then 0 else 1 end *
case when InternalDeadlineDate is null then 0 else 1 end *
case when ProjectDescription is null then 0 else 1 end *
case when Sales is null then 0 else 1 end *
case when Coop is null then 0 else 1 end *
case when PassThrough is null then 0 else 1 end *
case when POStatus is null then 0 else 1 end *
case when PONumber is null then 0 else 1 end as bit
)
as Flag
from t
now, that code works, but it's a bit lengthy, i was wondering if anyone knew of a better way to do this. please note that there are several data types being checked.
further details:
this code is in a view that is being looked at in an application for processing change orders. before a change order can be processed it must meet some data quality checks. this view shows if any of the required data is null.
Just add them up since NULL + "something" is always NULL ...
CREATE TABLE #test(column1 int,column2 varchar(4),column3 float)
INSERT #test VALUES(2,'2',2)
INSERT #test VALUES(0,'1',0)
INSERT #test VALUES(null,'1',0)
INSERT #test VALUES(1,null,0)
INSERT #test VALUES(0,'1',null)
INSERT #test VALUES(null,null,null)
SELECT CASE
WHEN column1 + column2 + column3 is NULL THEN 0 ELSE 1 END, *
FROM #test
from a post I created over 3 years ago ...
Keep in mind that if you have characters that are not numbers that you have to convert to varchar ...
INSERT #test VALUES(0,'abc',null)
Here is the conversion, no need to convert the varchar columns
SELECT CASE WHEN CONVERT(VARCHAR(100),column1)
+ column2
+CONVERT(VARCHAR(100),column3) is NULL THEN 0 ELSE 1 END,*
FROM #test
I think I might go with this solution unless someone comes up with a better one, inspired by #Alireza:
cast(
case when (ChangeOrderNumber is null or
a.ClientName is null or
a.QuoteNumber is null or
ClientNumber is null or
ServiceLine is null or
ServiceLineCode is null or
GroupLeader is null or
CreatedBy is null or
PTWCompletionDate is null or
BudgetedHours is null or
BudgetDollars is null or
InternalDeadlineDate is null or
ProjectDescription is null or
Sales is null or
Coop is null or
PassThrough is null or
POStatus is null or
PONumber is null) then 'false' else 'true'
end as bit) as Flag
Please use IIF() (need to be sql server 2012 or later) I really recommend:
IIF(column1 is null, '0', '1')
What about this one?
select not(a is null or b is null or ...)
You could invert the logic.
SELECT
CASE WHEN ChangeOrderNumber IS NOT NULL
AND ClientName IS NOT NULL
AND QuoteNumber IS NOT NULL
....
THEN 1
ELSE 0
END [Flag]
FROM t
Create a HasValue function that takes in a sql_variant and returns a bit. Then use bitwise AND in your SELECT clause.
CREATE FUNCTION dbo.HasValue(#value sql_variant) RETURNS bit
AS
BEGIN
RETURN (SELECT COUNT(#value))
END
GO
SELECT dbo.HasValue(ChangeOrderNumber)
& dbo.HasValue(ClientName)
& dbo.HasValue(QuoteNumber)
...
as [Flag]
FROM t
Or this:
declare #test1 char(1)
declare #test2 char(1)
declare #outbit bit
set #test1 = NULL
set #test2 = 'some value'
set #outbit = 'True'
select #test1
select #test2
If #test1 + #test2 IS NULL set #outbit = 'False'
Select #outbit
Much simpler -- just use the COALESCE function, which returns the value in the first non-null column.
SELECT Flag = CASE
WHEN COALESCE (column1, column2, column3, ...) IS NULL THEN 0
ELSE 1
END
FROM MyTable

Resources