How to add Order by in UNION - sql

SELECT
CASE WHEN ISNULL(TradeName,RegisteredName) ='' THEN '' ELSE CONCAT(ISNULL(TradeName,RegisteredName),' (',LocType,')') END [Description] ,'' [Param1]
FROM a.Table1
ORDER BY [Description] ASC
UNION ALL
SELECT '' [Code],'' [Description],'' [Param1]
ORDER BY [Description] ASC
I'm having this problem, when I tried ASC my Description I'm getting this error
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'UNION'.
Can anyone help me how to do it. Thanks

Two issues here.
union only gets a single order by and it must come at the end to handle the entire data set
when unioning two queries, they must have the same number of columns in each select statement. I've added a '' code, to the first select below, however you will need to fill that in with something that makes.more sense or perhaps a null instead.
SELECT
'' [code],
CASE
WHEN ISNULL(TradeName,RegisteredName) ='' THEN ''
ELSE CONCAT(ISNULL(TradeName,RegisteredName),' (',LocType,')')
END [Description],
'' [Param1]
FROM a.Table1
UNION ALL
SELECT
'' [Code],
'' [Description],
'' [Param1]
ORDER BY [Description] ASC

Related

CTE + INSERT INTO Error: String or binary data will be truncated

;
With CTE AS
(
SELECT IIF (ISNULL (POLHOLDERID,'') ='', Member_id, PolHolderId) AS RespMemberId,
CASE WHEN ( Member_id = PolHolderId) then 1 When ISNULL (PolHolderId,'') <> '' THEN 2 ELSE 3 END AS RespLevel ,
ROW_Number() OVER (PARTITION BY [Case Base#] ORDER BY CASE WHEN ( Member_id = PolHolderId) then 1 When ISNULL (PolHolderId,'') <> '' THEN 2 ELSE 3 END, DOB) AS RN,
* FROM [dbo].[AllHRS]
)
INSERT INTO dbo.Eligibility (
[CaseBaseNo]
,[RecordType]
,[HealthPlanId]
,[PlanId]
,[HPMemberId]
,[HPMemberId2]
,[FirstName]
,[MiddleName]
,[LastName]
,[Street1]
,[Street2]
,[City]
,[State]
,[Zip]
,[GroupNumber]
,[UserDefined1]
,[UserDefined2]
,[StartDate]
,[TerminationDate]
,[InitialActivationCode]
,[LoadAmount]
,[ServiceDate]
,[ServiceCode]
,[ServiceDescription]
,[HPReferenceNo]
,[IssueNewCard]
,[Language]
,[Filler])
SELECT
[Case Base#] as CaseBase,
'117A' as RecordType,
'H81' as HealthPlanID,
'H81-117A' as PlanId,
RespMemberId AS MemberId,
null,
IIF (ISNULL (POLHOLDERID,'') ='', Member_First_Name, IIF(Charindex(',', PolHolderName)> 0, Substring(PolHolderName, 1,Charindex(',', PolHolderName)-1), PolHolderName)),
NULL,
IIF (ISNULL (POLHOLDERID,'') ='', Member_Last_Name, Substring(LTRIM(IIF(Charindex(',', PolHolderName)> 0, Substring(PolHolderName, Charindex(',', PolHolderName)+1,LEN(PolHolderName)), PolHolderName)),1,charIndex(' ',
LTRIM(IIF(Charindex(',', PolHolderName)> 0, Substring(PolHolderName, Charindex(',', PolHolderName)+1,LEN(PolHolderName)), PolHolderName))+' '))),
ADDRESS1,
ADDRESS2,
CITY,
STATE,
ZIP,
[Case Base#],
NULL,
NULL,
FORMAT(GETDATE(), 'MM/dd/yyyy') AS [START DATE],
IIF([Member TermDate] is null, '',
DATEADD(month,30,[Member TermDate])),
NULL,
0.00,
[INTERVIEW DATE],
CASE
WHEN Clinical_Variable not like '%57' and Clinical_Variable not like '%58' THEN 'HRS'
WHEN Clinical_Variable like '%57' THEN 'HRA'
WHEN Clinical_Variable like '%58' THEN 'CC'
END as Service_Code,
NULL,
0.00,
'YES',
NULL,
NULL
FROM CTE WHERE RN =1
Little background. We get a file from our reporting department. It is IT's job to do a bunch of aggregations and shove it into another file, an eligibility file.
The error says:
Msg 8152, Level 16, State 13, Line 2
String or binary data would be truncated.
The statement has been terminated.
Can someone help? Anyone know what's going on?
From the error its evident that for one of the columns(or more) the data you are trying to set is bigger than the column size.. I would look at the name columns and the address columns. An easy way to debug this would be to put a MAX(LEN()) around the columns in your select clause and compare it with your table definition.

Syntax error near "Order By" - 'Incorrect syntax near the keyword 'ORDER'.'

I have been staring at this for too long and I can't seem to see where I went wrong.
I have a stored procedure that has to return a bunch of data where the "ExtractedText" matches the word the person is searching for:
Select #Command = 'select DISTINCT CaseFileEvents.InvestigatorID,convert(nvarchar,EventDate,111) as ''EventDate'',EventTime,EventDesc,TaskID,Privileged,Private,Email,HasAttachments,FName,LName, FName + '' '' + LName as Name ,CaseFileEvents.FileID,CaseFiles.FileName,ItemEntryGradeID, EventDescPlainText
from CaseFileEvents
join ......
WHERE '+ #FilterField +' LIKE ''%' + #FilterQuery + '%'' ORDER BY ' + #SortName + ' ' + #SortOrder + ''; this area seems to bug out
#FilterField is a column in one of the tables, #FilterQuery is the word the user typed in that it is looking for. #SortName, is the name by wich it gets sorted.
Command examples: #FilterField = "ExtractedText", #FilterQuery="something", #SortName="EventID", #SortOrder="desc"
This is the error:
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'ORDER'.
Full command:
WHERE ExtractedText LIKE '%add%' ORDER BY EventID desc;
You cannot order by variable. You need to use dynamic SQL:
SELECT
*
FROM
My_Table
WHERE
Whatever = #something
ORDER BY
CASE #sort_order
WHEN 'ASC' THEN
CASE #order_by
WHEN 'surname' THEN surname
WHEN 'forename' THEN forename
WHEN 'fullname' THEN fullname
ELSE surname
END
ELSE '1'
END ASC,
CASE #sort_order
WHEN 'DESC' THEN
CASE #order_by
WHEN 'surname' THEN surname
WHEN 'forename' THEN forename
WHEN 'fullname' THEN fullname
ELSE surname
END
ELSE '1'
END DESC
Look in this post:
Can I store SQL Server sort order in a variable?
The reason why it didn't work is because I was missing
WHERE EventID = convert(nvarcahr,#EventID)
and just took out "DISTINCT"

SQL: Combine value into one result when NULL or empty

I have a SQL query that returns two columns - "Title" and "Count". When "Title" is NULL or empty (''), I want to combine the result into one row. How can I do this?
This is what I have so far:
SELECT [Title] WHEN '' THEN 'blank' ELSE ISNULL([Title],'blank') AS [Title],
COUNT([value]) AS [Count]
FROM ....
WHERE ....
GROUP BY [Title],[Count]
but because of the Group By, they are split into two different rows:
SELECT CASE WHEN COALESCE([Title],'') = '' THEN 'blank'
ELSE [Title]
END AS [Title],
COUNT([value]) AS [Count]
FROM ....
WHERE ....
GROUP BY CASE WHEN COALESCE([Title],'') = '' THEN 'blank'
ELSE [Title]
END
An alternate to Joe Stefanelli's solution:
Select Case
When Len( [Title] ) > 0 Then [Title]
Else 'blank'
End
From ...
Group By Case
When Len( [Title] ) > 0 Then [Title]
Else 'blank'
End
Having the [Count] column in the GROUP BY clause seems suspicious... does it work if you only group by [Title]?
COALESCE
select title_id,count(*),COALESCE(type,pub_id)
from titles
group by
title_id,type,pub_id

Extracting First Name and Last Name

I have a column named Name in a table called test which has Full name and I am trying to extract First name and Last Name. So I wrote query something like this:
SELECT
[Name],
LEFT([Name],CHARINDEX(' ',[Name])-1) AS FIRST_NAME,
SUBSTRING([Name],CHARINDEX(' ',[Name])+1,LEN([Name])) AS LAST_NAME
FROM Test
But It is giving me error saying:
Msg 537, Level 16, State 2, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
Thta's because I have some values in the name like:
Name:
Hopkins
How do I handle these?
Declare #t table ( [Name] varchar(100) )
insert into #t ( Name )
VALUES ( 'dennis hopper' ), ('keanu reaves'), ('thatgirl')
SELECT
[Name],
CHARINDEX(' ', [Name]),
CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
LEFT([Name],CHARINDEX(' ',[Name])-1)
ELSE
[Name]
END as FIRST_NAME,
CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
SUBSTRING([Name],CHARINDEX(' ',[Name])+1, ( LEN([Name]) - CHARINDEX(' ',[Name])+1) )
ELSE
NULL
END as LAST_NAME
FROM #t
The problem with your original code is here:
CHARINDEX(' ',[Name])-1
If [Name] does not contain a space, CharIndex returns 0. You subtract 1 and feed this in to the Left function. When the 2nd parameter to the left function is -1, you will get this error. In my opinion, the easiest way to "fix" this problem is to give the CharIndex function something to find, like this:
CHARINDEX(' ',[Name] + ' ')-1
Now... this code cannot fail.
You only NEED to do this one place in your original code, but you should add it to the LAST_NAME part also. If you don't, you will get incorrect results (eventhough you will not get an error).
SELECT [Name],
LEFT([Name],CHARINDEX(' ',[Name] + ' ')-1) AS FIRST_NAME,
SUBSTRING([Name],CHARINDEX(' ',[Name] + ' ')+1,LEN([Name])) AS LAST_NAME
FROM Test
This query will return the same results as the query suggested by #Sage, but (in my opinion) it is easier to read, and easier to understand.
we may also use locate function
SELECT
Name,
LEFT(Name,locate(' ',Name)-1) AS FIRST_NAME,
SUBSTRING(Name,locate(' ',Name)+1,LENgth(Name)) AS LAST_NAME
FROM test

What's the Purpose of "MAX(SUBSTRING(CONVERT(X),1,DATALENGTH(CONVERT(X))*1 or 0))" in SQL?

I have inherited a stored procedure which has code like the following. It's sort of a poor-man's PIVOT, I think (has to run on SQL Server 2000).
SELECT
[TheDate] = MAX(
substring(
CONVERT(VarChar(100), thedate, 101),
1,
datalength(CONVERT(VarChar(100), thedate, 101)) *
( CASE index WHEN 123 THEN 1 ELSE 0 END ))),
[Scaled] = MAX(
substring(
CONVERT(VarChar(100), Scaled),
1,
datalength(CONVERT(VarChar(100), Scaled)) *
( CASE index WHEN 123 THEN 1 ELSE 0 END ))),
[Value] = MAX(
substring(
CONVERT(VarChar(100), [Value]),
1,
datalength(CONVERT(VarChar(100), [Value])) *
( CASE index WHEN 123 THEN 1 ELSE 0 END ))),
-- Repeat for other values of "index"
GROUP BY other columns
Has anyone seen this construct before? Not the "pivot" stuff, but rather the
MAX(SUBSTRING(CONVERT(X),1,DATALENGTH(CONVERT(X))*1 or 0))
Why not just use
MAX(CASE index WHEN 123 THEN [Value] ELSE NULL END)
?
Interesting quote
It's sort of a poor-man's PIVOT
I happen to know that the PIVOT operator is the emperor's new clothes on top of multiple CASE statements. In fact that is how the query plan appears. So there is more than one way to look at it.
Martin's use of LEFT(, length) is the shortcut for doing a convert to a particular length, since LEFT (and RIGHT) implicitly converts the first argument.
There is one case where it won't work though, for the CONVERT(varchar, date, 101) which is a specific format.
DATALENGTH(CONVERT(X))*1 or 0)
This may have been an attempt to size the resultant columns based on the maximum length in the columns, but clearly this is not the right code (if that is the purpose).
MAX(CASE index WHEN 123 THEN [Value] ELSE NULL)
Looking much better. "index" is a keyword so if you copied your snippet from working code, I would be surprised. Maybe it works in 2000?
Some tips:
brackets around "index"
missing "end" for case
missing CONVERT (the data does not seem to be varchar, so you need to convert)
the original returns '' not NULL when it is not 123
MAX(CASE [index] WHEN 123 THEN CONVERT(varchar(100), [Value], 101) ELSE '' END)
(I threw in the 101 for [value] to be consistent with the date format. It has no effect on numerics)