I want to have a select that will not have fixed number of columns. Column OptionalColumn
should be selected only if variable @check = 1
This is what I had (syntax is bad but maybe it explains my problem)
SELECT
Column1, Column2,
(IF @Check = 1
BEGIN OptionalColumn END)
FROM table
It is crucial to have it only if @Check = 1 and not having it if @Check = 0. Is it doable?
You could do this with an IF ELSE block like this;
CREATE TABLE #table (Column1 varchar(10), Column2 varchar(10))
INSERT INTO #table
VALUES
('column1', 'column2')
DECLARE @Check bit; SET @Check = 0
IF @Check = 1
(SELECT Column1, Column2
FROM #table)
ELSE
(SELECT Column1
FROM #table)
Change the variable from 0 to 1 for testing to see the change in number of columns.
Rich Benner gave you a good solution, as an alternative you can use dynamic sql like that :
DECLARE @sqlvar VARCHAR(100)
select @Sqlvar= ' SELECT Column1, Column2 '+IIF (@check=1,',OptionalColumn','')+' from TABLE';
EXECUTE sp_executesql @sqlvar
For reference on sp_ executesql look: [https://msdn.microsoft.com/it-it/library/ms188001(v=sql.120).aspx]
Can use IF ELSE block. Please try this.
--Creating a Table.
CREATE TABLE #MyTable
(
Column1 VARCHAR(10),
Column2 VARCHAR(10),
OptionalColumn VARCHAR(10)
)
--Inserting value to the Table.
INSERT INTO #MyTable
VALUES('Value 1', 'Value 1','Optional Value')
--IF ELSE Logic to desired output.
DECLARE @Check bit
SET @Check = 0
IF @Check = 1
(
SELECT
Column1,
Column2
FROM
#MyTable
)
ELSE
(
SELECT
Column1,
Column2,
OptionalColumn
FROM
#MyTable
)
I find that it's pretty clean and readable to use temp tables for this purpose, and it doesn't require duplicating queries or big branches of logic.
Create a temp table with all the columns you would ever need. Use IF statements to drop the columns you don't want to display from the temp table. Then finally, select * from the temp table.
This will also allow you use the data returned to make a determination on whether to keep the column or not.
IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL DROP TABLE #tempTable;
select '---' as [1],
'---' as [2],
'---' as [3],
'---' as [4],
'---' as [5],
'---' as [6],
'---' as [7],
null as [8]
into #tempTable
if RAND() > .5
begin
alter table #tempTable drop column [1]
end
if RAND() > .5
begin
alter table #tempTable drop column [2]
end
if RAND() > .5
begin
alter table #tempTable drop column [3]
end
--Query using result set to dertmine if column should be dropped
if (select count(*) from #tempTable where [8] is not null) = 0
begin
alter table #tempTable drop column [8]
end
select * from #tempTable
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.