SQL invalid Identifier query - sql

I am getting an error that grandvisit is an invalid identifier, and I am unsure if I will get it with other identifiers either. Any light shed on this would be amazing. As I cannot see why it differents from others.

You cannot refer the alias names in same select clause where it is generated.
SELECT Sum(aerosolvisit + hazvisit + hvvisit + hlopvisit
+ plvisit + miniloadvisit + aprvisit + apr2visit
+ aprawkvisit) AS grandvisit
To calculate grandratio you are using the below expression which uses the alias name grandvisit
SELECT CASE
WHEN Sum(grandtotal) = 0 THEN 0
WHEN Sum(grandvisit) = 0 THEN 0
ELSE Sum(grandtotal) / Sum(grandvisit)
END AS grandratio
You can use derived table to do this
SELECT CASE
WHEN Sum(grandtotal) = 0 THEN 0
WHEN Sum(grandvisit) = 0 THEN 0
ELSE Sum(grandtotal) / Sum(grandvisit)
END AS grandratio
From
(
SELECT Sum(aerosolvisit + hazvisit + hvvisit + hlopvisit
+ plvisit + miniloadvisit + aprvisit + apr2visit
+ aprawkvisit) AS grandvisit
...
) A
Note : You are using old style outer join's(+=). It is better to use Right/Left joins which is more readable

Related

some weird signs appearing on SQL SERVER Query output

i have written a SELECT Query on SQL SERVER 2014 . I have got the desired output . but an apostrophe symbol(') appearing on 'TaskAction' field data(at the end of each data). here it is my script:
SELECT
WOtask.PK,
WOPK,
TaskNo,
TaskAction =
CASE
WHEN WOTask.AssetPK IS NOT NULL THEN '<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' + CASE
WHEN Asset.Vicinity IS NOT NULL AND
Asset.Vicinity <> '''' THEN RTRIM(Asset.Vicinity) + ': '
ELSE ''''
END + WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
ELSE WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
END,
Rate,
Measurement,
Initials,
Fail,
Complete,
Header,
LineStyle,
WOtask.Comments,
WOtask.NotApplicable,
WOTask.Photo1,
WOTask.Photo2
FROM WOtask WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WOTask.AssetPK
LEFT OUTER JOIN AssetSpecification
ON AssetSpecification.PK = WOTask.AssetSpecificationPK
WHERE (WOPK IN (SELECT
WOPK
FROM WO WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WO.AssetPK
LEFT OUTER JOIN AssetHierarchy WITH (NOLOCK)
ON AssetHierarchy.AssetPK = WO.AssetPK
WHERE WO.WOPK = 10109)
)
ORDER BY WOPK, TaskNo
now please check my output and error
please help to solve this issue. Thanks in Advance.
As noted in comments, use ELSE '' instead of ELSE ''''. The reason is that within a pair of single quotes, then '' tells SQL to escape a single quote into your output.
For instance, to show the output User's, you would need SELECT 'User''s'.

Ordering SQL SELECT by result of a string comparison

I have a table with two string columns, ID and LANGUAGE. Language can be one of CYM, ENG, GAE.
When selecting data from the table, I want to order it by the language column, putting a specified language at the start of the results, with the other languages later, in any order.
Say I have the data
+===+=====+
+ 1 + CYM +
+ 2 + GAE +
+ 3 + ENG +
+ 4 + CYM +
+===+=====+
and I want the output to be
+===+=====+
+ 3 + ENG +
+ 1 + CYM +
+ 2 + GAE +
+ 4 + CYM +
+===+=====+
How do I do the equivalent of
SELECT ID, LANGUAGE
FROM TABLE
ORDER BY (LANGUAGE = 'ENG'), ID
You can use CASE WHEN to ensure ENG will be first:
SELECT ID, LANGUAGE
FROM your_table
ORDER BY
CASE LANGUAGE WHEN 'ENG' THEN 0
ELSE 1
END ASC;
-- ,ID ASC -- if needed
LiveDemo

CAST number as varchar, then update into another table as date

I'll as brief as possible, but start by saying I'm a network guy, not a DBA.
SQL Server Enterprise 11.0.5343
Scenario - Need to get three columns (each with a part of a date) together, and then update another table with the full date.
Source table: UT210AP
Columns:
UTONMM (Utility On Month - 2 digit)
UTONDD (Utility On Day - 2 digit)
UTONYY (Utility On Year - 2 digit)
UTONCV (Utility On Century - 0 = 19xx, 1 = 20xx)
I can select the data into a "date" with this code (the source data is on an IBM AS/400 linked server)
CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
CASE WHEN UTONCV = '1'
THEN
RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4),UTONYY),2)),4)
ELSE
RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END AS UTON
And I get these results in the column I named "UTON":
4/6/1994
7/1/1988
11/14/1990
6/6/2014
QUESTION:
I have a nightly import job that runs, and I need to get the "date" (like 4/6/1994) into a field called TIME_CONNECT as part of this update statement from the job:
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0
The "UTOFMM" in the code above is "Utility Off Month", I don't even care about checking for it's value, I just want to get the "UTON" date from the top select statement into the "TIME_CONNECT" field in the "Temp_RX_CUSTOMERS" field.
Is this what you want? This copies the value into the field, assuming time_connect is a string.
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID,
time_connect = (CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
(CASE WHEN UTONCV = '1'
THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4),UTONYY),2)),4)
ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END)
)
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf
ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0;
If time_connect is a date/datetime data type, you can use datefromparts() (available in SQL Server 2012+):
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID,
time_connect = DATEFROMPARTS(1800 + UTONCV * 100 + UNONYY,
UTONMM, UTONDD)
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf
ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0;

how to parse for more than 4 positions

I have a funny case where a piece of data needed, is actually embedded in a column of data looking something like this:
note that is a shop with strong legacy mess still in place.
adlu201008270919_3.zip the date is what i need and is embedded.
I have code to do this here:
AND CAST(SUBSTRING(M.MDS_FILE,5,4) + '-' + SUBSTRING(M.MDS_FILE,9,2) + '-' + SUBSTRING(M.MDS_FILE,11,2) as datetime)
But now I find out that where you have here 'adlu' that is 4 pos. It can be 3 or 2 or 1.
So I have to code for that I have come up with this: but it's not compiling:
AND CASE WHEN WHEN CAST(SUBSTRING(M.MDS_FILE,5,4) + '-' + SUBSTRING(M.MDS_FILE,9,2) + '-' + SUBSTRING(M.MDS_FILE,11,2) as datetime)
ELSE WHEN OEN.LENGTH(S.FACILITY_KEY) = 3 THEN CAST(SUBSTRING(M.MDS_FILE,4,4) + '-' + SUBSTRING(M.MDS_FILE,8,2) + '-' + SUBSTRING(M.MDS_FILE,10,2) as datetime)
ELSE WHEN OEN.LENGTH(S.FACILITY_KEY) = 2 THEN CAST(SUBSTRING(M.MDS_FILE,3,4) + '-' + SUBSTRING(M.MDS_FILE,7,2) + '-' + SUBSTRING(M.MDS_FILE,9,2) as datetime)
ELSE CAST(SUBSTRING(M.MDS_FILE,2,4) + '-' + SUBSTRING(M.MDS_FILE,6,2) + '-' + SUBSTRING(M.MDS_FILE,8,2) as datetime) END
CASE requires an evaluation. Your first statement just says WHEN(a bunch of conversions) but there's never an evaluation (=, <, > etc).
I'm assuming you want that to be AND CASE WHEN OEN.LENGTH(s.FACILITY_KEY) = 4 THEN ...
Instead of a CASE statement based of S.FACILITY_KEY, I would use PATINDEX to dynamically find the start position of the date string that you're looking for:
DECLARE
#TestValue1 VARCHAR(50),
#TestValue2 VARCHAR(50),
#TestValue3 VARCHAR(50),
#TestValue4 VARCHAR(50)
SET #TestValue1 = 'adlu201008270919_3.zip'
SET #TestValue2 = 'adl201008270919_3.zip'
SET #TestValue3 = 'ad201008270919_3.zip'
SET #TestValue4 = 'a201008270919_3.zip'
SELECT CAST(SUBSTRING(#TestValue1, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue1), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue2, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue2), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue3, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue3), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue4, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue4), 8) AS DATETIME)

Complex SQL CASE WHEN

I am trying to do a SELECT using a CASE statement, and I 'm getting errors that do not make sense. My statement appears to adhere to any SQL syntax rules but I'm getting the good ol' "the multi part identifier to_do.[item_id] AND to_do.[item] cannot be bound.
This does not make sense because the column names are correct with respect to the table columns.
Here is the SQL:
SELECT to_do.[item_id],
to_do.[item] = CASE to_do.encounter_id WHEN 0 THEN CONVERT(NVARCHAR, e.[date], 101 ) + ' - ' + p.[first_name] + ' ' + p.[last_name] + ' - ' + to_do.[item] AS to_do.[item] ELSE to_do.[item] END,
to_do.[complete],
to_do.[encounter_id],
e.[date],
p.[last_name] + ', ' + p.[first_name] AS [p_name]
FROM [dbo].[to_do] LEFT OUTER JOIN
[dbo].[encounter] e ON
to_do.[encounter_id] = e.[encounter_id] LEFT OUTER JOIN
[dbo].[patients] p ON
e.[mrn] = p.[mrn]
WHERE to_do.[user_id] = #user_id
Any ideas what I'm doing wrong here ? Based off previous experience I should be able to use CASE like this but maybe I've just been staring at it too long and don't see the obvious.
Thanks!
You can't use a table prefix in a column alias to_do.[item] = CASE ... is presumably intended to be [item] = CASE ...
(Also you have a rogue AS in the middle of the CASE itself that needs removing)
The AS {alias} needs to go after the END. I'd rewrite as follows:
SELECT to_do.[item_id],
CASE to_do.encounter_id WHEN 0 THEN CONVERT(NVARCHAR, e.[date], 101 ) + ' - ' + p.[first_name] + ' ' + p.[last_name] + ' - ' + to_do.[item] ELSE to_do.[item] END AS [item] ,
...
Your AS is in the wrong place-- try
to_do.[item] = CASE to_do.encounter_id WHEN 0 THEN CONVERT(NVARCHAR, e.[date], 101 ) + ' - ' + p.[first_name] + ' ' + p.[last_name] + ' - ' + to_do.[item] ELSE to_do.[item] END AS to_do.[item] ,