Return Value Column Name - sql

The stored procedure below works correctly as expected. Returning True if "FleetBarcode" exists and False if it doesn't.
However, when it returns it it displays it as below
(no column name)
True
My problem is I need the "No Column Name" part to have a defined column name. Tried the method below so far which gives the 'True' field an alias.
Thank you for your time.
ALTER proc [dbo].[usp_getjobs]
#barcode as nvarchar(20)
as
SELECT CASE WHEN EXISTS(
SELECT
[FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1
)
THEN (SELECT 'True' 'Exist')
ELSE (SELECT 'False' 'Exist')
END

Use
ALTER PROC [dbo].[usp_getjobs] #barcode AS NVARCHAR(20)
AS
SELECT CASE
WHEN EXISTS(SELECT [FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1) THEN 'True'
ELSE 'False'
END AS [Exist]
The alias needs to go on the outer SELECT.
Also for column aliasing it is more common to use square brackets than single quotes.

Get rid if the SELECTs in the THEN/ELSE blocks and use AS to give the column a name:
SELECT CASE WHEN EXISTS(
...
THEN 'True')
ELSE 'False')
END AS [Exist] --<-- add name here

ALTER proc [dbo].[usp_getjobs]
#barcode as nvarchar(20)
as
SELECT CASE WHEN EXISTS(
SELECT
[FleetBarcode],
[Deleted]
FROM w_DeliveryItems
WHERE FleetBarcode = #barcode
AND Deleted != 1
)
THEN (SELECT 'True' 'Exist')
ELSE (SELECT 'False' 'Exist')
END AS [Your Column Name]

Related

How to select multiple columns from a table in an IF ELSE stored procedure

I am trying to create a stored procedure which has 3 IF ELSE sections, in one of them I would like to select 2 columns to evaluate but am getting this error :
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
In this case the guid&number are unique, here is the section of the procedure in question:
IF ((SELECT [guid],[number] from [tws] where [guid] = #ReferenceNumber and #Number = [number] and ([instruction_submitted] = '' or [instruction_submitted] is null )) is not null)
SET #ReturnValue = 2
ELSE ```
I think you want exists:
IF (EXISTS (SELECT [guid],[number]
from [tws]
where [guid] = #ReferenceNumber and #Number = [number] and
([instruction_submitted] = '' or [instruction_submitted] is null )
)
)
BEGIN
SET #ReturnValue = 2;
END;
ELSE . . .
I also strongly encourage you to use BEGIN/END around in IF statements -- that makes it less error-prone to add additional statements in the future.

SQL: CASE expression with declared variable

I have following example that doesn't work in SQL server.
table1.field1 is also a char(3)
DECLARE #CALCULATED_FIELD char(3);
SELECT table1.field1
,table1.field2
,CASE
WHEN table1.field2 = '1' THEN #CALCULATED_FIELD = table1.field1
ELSE #CALCULATED_FIELD = 'ALL'
END
FROM table1
Anyone knows the problem with the case statement?
A SQL Server SELECT statement can either assign variable values or return rows, but not both. You might intend:
SELECT #CALCULATED_FIELD = COALESCE(table1.field1, 'ALL')
FROM table1;
This would assign the maximum value to the variable -- and the only value if the table has only one row. If the table has no rows, the variable would be assigned 'ALL'.
The result of the CASE expression must be assigned to the variable, but it is not allowed in the same statement to return any columns from the table.
So this:
SELECT
#CALCULATED_FIELD = CASE
WHEN field2 = '1' THEN field1
ELSE 'ALL'
END
FROM table1
is syntactically valid, although it will assign to the variable finally, the result of the CASE expression of the last row fetched.
By the name of the variable, I suspect that you want a 3d column which will be calculated by CASE:
SELECT field1, field2,
CASE
WHEN field2 = '1' THEN field1
ELSE 'ALL'
END calculated_field
FROM table1
See a simplified demo.
I would use a scaler funtion in this case
CREATE FUNCTION calcfield
(
#field2 VARCHAR(4),
#field1 VARCHAR(4)
)
RETURNS VARCHAR(3)
AS
BEGIN
DECLARE #CalcField CHAR(3)
SELECT #CalcField = CASE
WHEN #field2 = '1' THEN #field1
ELSE 'ALL'
END
RETURN #CalcField
END
GO
and then change your query to
SELECT table1.field1
,table1.field2
,dbo.calcfield(table1.field2,table1.field1)
FROM table1
Expressions like A=B is not a scalar value. So when you run the following query, it fails and you will get an error Incorrect syntax near '='.
SELECT ('aaa' = 'aaa')
In your case
CASE WHEN table1.field2 = '1'
THEN #CALCULATED_FIELD = table1.field1
ELSE #CALCULATED_FIELD = 'ALL'
END
is not a valid expression, and you might mean something like
CASE WHEN table1.field2 = '1'
THEN (CASE WHEN #CALCULATED_FIELD = table1.field1 THEN 1 ELSE 0)
ELSE (CASE WHEN #CALCULATED_FIELD = 'ALL' THEN 1 ELSE 0)
END
Please note that you can run a query like
SELECT columnName = 'aaa'
and it works as
SELECT 'aaa' AS columnName
Thx a lot.
For the create function, I have no rights and we can't do it on the production environment. But would work. Nice.
The example from forpas used and it works perfect for me.

how to use declared variable to select data from another table in case when condition?

I made select query in which i want to select data based on condition.For this i declared one variable and set value of that variable in else part.I want to use that variable for further select in same else part how can i achieve this?Please Help
declare #stateid int
select CASE WHEN MstCustomerAddressInfo.StateId is null
THEN 24
ELSE set #stateid = MstCustomerAddressInfo.StateId
select mststate.statecode from mststate where MstState.StateId = #stateid
END AS StateCode
No, you can't have SET inside a CASE expression. Even you can't have multiple statements.
Same query you can write as following.
declare #stateid int
select CASE
WHEN MstCustomerAddressInfo.StateId is null THEN 24
ELSE
-- set #stateid = MstCustomerAddressInfo.StateId
(select mststate.statecode
from mststate
where MstState.StateId = MstCustomerAddressInfo.StateId)
END AS StateCode
from [Your_Table]

Conditional SQL statement - conditioning on column to be returned

I'm trying to make a conditional select statement, and the parameter I'm conditioning on is the column I want to return. Meaning - if something about a column in a table is true, I want to return that column; if not, I want to return the other column.
Ex:
IF table.obj_param_A = ?
BEGIN
SELECT obj_param_A FROM table
END
ELSE
BEGIN
SELECT obj_param_B FROM table
END
I know this doesn't work, but it's the general idea of what I want. Any idea how to structure this properly?
If you do not concern the column name returned, you can use CASE
SELECT
CASE
WHEN obj_param_A = ? THEN obj_param_A
ELSE obj_param_B
END AS value
FROM table
Below is an example of how you can use the table information about a specific column in order to select from specific columns.
Drop Table dbo.Test
Create Table dbo.Test (iVersion int, iVersion2 smallmoney)
Insert Into dbo.Test
Select 1, 1.12
Declare #Test as nvarchar(200)
Select #Test = Column_Name from information_schema.columns where Table_Schema = 'dbo' and table_name = 'test' and Ordinal_Position = 1
--IF (#Test = 'iVersion') --Equal To iVersion
IF (#Test != 'iVersion') ---Not Equal To iVersion
BEGIN
SELECT iVersion FROM dbo.Test
END
ELSE
BEGIN
SELECT iVersion2 FROM dbo.Test
END
This should return the data from iVersion2 since the Name of the First column is "iVersion" and the If Statement returns iVersion only if it is not the first column

Using Case Statement in SQL with parameter/variable to check for Null values

I am trying to write a SQL Select statement to return records based on a user input through a front end.
I want to write the Select statement like this:
SELECT somefields
FROM sometable
WHERE CASE variable
WHEN 'blank' THEN field IS NULL
ELSE field = field
END
Basically I either want to filter a column to find NULL values or ignore the filter and return all values depending on the value of the variable. I know that the results of the CASE statement is not executable but how can I do this?
When variable is 'blank', the following query will give you rows where field is NULL. When variable is anything else, it will give you all rows:
SELECT somefields
FROM sometable
WHERE
(variable = 'blank' AND field IS NULL)
OR (variable <> 'blank')
You can use NULLIF() (link is for SQL Server, but NULLIF() should be standard):
SELECT somefields
FROM sometable
WHERE field = NULLIF(variable, 'blank')
The following snippet should behave as follows:
when #variable is null, return all rows
when #variable = 'blank', return all rows where field is null or field = 'blank'
otherwise, return rows where #variable equals field
Code snippet:
WHERE 1 = CASE
WHEN #variable is null then 1
WHEN #variable = 'blank' and field is null then 1
WHEN #variable = field then 1
END
SELECT somefields
FROM sometable
WHERE ((variable IS NULL OR variable = 0) OR (variable = field))
WHERE Criteria is apply when variable have value
For Example:
DECLARE #CityName VARCHAR(50)
SET #CityName = NULL
SELECT CityName
FROM City
WHERE ((#CityName IS NULL ) OR (#CityName = CityName ))
When City is null then tables return all rows
I think I get what you're after. Something like this maybe?
SELECT field1,
field2,
CASE variable
WHEN 'blank' THEN NULL
ELSE field3
END as field3
FROM sometable
Think I understand what you mean....for example....
SELECT
House, Postcode
from
SomeTable
where
(House=isnull(#House,House) or (House is null and #House is null))
and
(Postcode=isnull(#Postcode,Postcode) or (Postcode is null and #Postcode is null))
First bit of the conditional where is to use the variable, when present (the isnull bit is to ignore the variable if it's null)
Second bit of the conditional where is in case your evaluative field is null also as effectively fields don't = null they are 'is null'.
Confused? Good. Works on what I'm doing though!
Here is my solution based on #Andomar answer above aimed at anyone testing an input varchar value, you need to test the parameter in the right order as per the example below:
FIELD1 = CASE
WHEN #inputParameter = '' THEN FIELD1
WHEN #inputParameter <> FIELD1 THEN NULL -- if input is some text but does not match
WHEN #inputParameter IS NULL THEN FIELD1
WHEN #inputParameter != '' AND FIELD1 = #inputParameter THEN FIELD1
END
Hope this helps someone.