Conditional SQL statement - conditioning on column to be returned - sql

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

Related

SQL:How to create SQL table using some condition [Create table only when condition is true]

Create table tblname if(name='stack').
Create this table only when this condition is true , So how to write this type of query?
I am not an expert...YET!
But you can try the below query with a IF statement In Another If Statment.
It's Difficult to help if we don't know what your end goal is??
DECLARE #Condition Varchar(5) = 'TRUE'
IF(#Condition='True')
BEGIN
IF NOT EXISTS (SELECT object_id FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Country]') AND type = 'U')
BEGIN
CREATE TABLE [dbo].Country(ID INT, Description Varchar(20))
END
END;
ELSE
BEGIN
PRINT 'IGNORE - DONT CREATE TABLE'
END;

There is already an object named '#BaseData' in the database

Below is a snippet of my code.
I am wanting to filter my data based upon a variable.
When I try to run the code, it returns an error of "There is already an object named '#BaseData' in the database.". I am not sure as to why this is the case; I have put extra checks within the IF statements to drop the temp table if it already exists but to no avail.
Are you able to help or provide an alternative solution please?
DECLARE #Variable AS VARCHAR(20) = 'Example1'
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
IF #Variable = 'Example1'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
END
IF #Variable = 'Example2'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 1
END
IF #Variable = 'Example3'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 0
END
While code is compiled by SQL, creation of same #table is found in each condition so it doesn't work.
One possible solution would be to create table and than insert data conditionally.
-- DROP TEMP TABLE IF EXISTS
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
GO
-- CRATE TEMP TABLE WITH TempId, AND SAME STRUCTURE AS YOUR TABLE
SELECT TOP 0 CONVERT(INT, 0)TempId, * INTO #BaseData FROM TestTable
-- DECLARE VARIABLE
DECLARE #Variable AS VARCHAR(20)= 'Example1'
-- INSERT DATA IN TABLE DEPENDING FROM CONDITION
IF (#Variable = 'Example1')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable
END
IF (#Variable = 'Example2')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 1
END
IF (#Variable = 'Example3')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 2
END

SQL select statement with WHERE clause based on name

I have a table TBL_TEST which has a column NAME with 5 rows, and those rows have the values 'Balkhab', 'Gosfandi', 'Sancharak', 'Aqcha'
I want to write a query with a WHERE clause that when the value in where class match with one of the values in NAME column in TBL_TEST then it should show only that value but when it does not match then it should show all the values in the table, below is select statement that is not working as expect.
SELECT NAME
FROM TBL_TEST
WHERE NAME = 'Balkhab' OR NAME != 'Balkhab'
I suspect you want something like this:
SELECT NAME
FROM TBL_TEST
WHERE NAME = 'Balkhab'
UNION ALL
SELECT NAME
FROM TBL_TEST
WHERE NOT EXISTS (SELECT 1 FROM TBL_TEST WHERE NAME = 'Balkhab');
IF Exists(select 'X' FROM TBL_TEST WHERE NAME = 'Balkhab')
SELECT NAME from TBL_TEST WHERE NAME = 'Balkhab'
ELSE
SELECT NAME FROM TBL_TEST
You can try this one below
select *
from table where not exists (select name from table where name = 'Aqcha') or
name ='Aqcha'
You can write a stored procedure for it with one parameter.
Create procedure(#Name varchar(max))
As
begin
If(Isnull(#name, 0))
Begin
If exists (select 1 from TBL_TEST xx where xx.name = #name)
Begin
Select *
From TBL_TEST
Where name = #name
End
Else
Begin
Select *
From TBL_TEST
End
End
Else
Begin
Select * from TBL_TEST
End
End
Pass your name as parameter to the stored procedure to get require result
stored procedure are the best option as you can avoid network traffic, less bandwidth as you can pass only require parameter and get required result

Return Value Column Name

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]

Display all records of a table unless I pass a key

Is there an other way to get all rows of a table using a stored procedure unless I pass the procedure a key?
If so, how can I code that in SQL Server?
try this
CREATE PROCEDURE GetData(#key int = null)
BEGIN
SELECT * FROM Table WHERE (#Key Is NULL or id = #Key)
END
You could also use the COALESCE operator:
CREATE PROCEDURE dbo.uspMySprocName(#Key INT = NULL)
AS
BEGIN
SELECT * FROM MyTable WHERE ID = COALESCE(#Key, ID);
END
you can use a if condition and have 2 queries
**syntax:**
if (#key is null ) then
begin
select * from table1 ;
end
else
being
select * from tabel1 where field1 = #key ;
end
endif
The following link should help
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=146620