Is it possible to check for a column existence within an inline statement? Please note this is not a duplicate to common question "How to check if column exist." This relates to a possible INLINE solution.
There are may ways to do this but since this needs to be written for BCP [out] command I cannot use SPs and the compatibility has to match MSSQL 2000.
Would anything similar to the following have chance to work?
SELECT
[col1],
[col2],
CASE
WHEN (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Table' AND COLUMN_NAME = 'col3') = 1
THEN [col3]
ELSE null
END
FROM [MyDb].[dbo].[Table]
or sub-query way like this....
SELECT
[col1],
[col2],
SELECT(if exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Table' AND COLUMN_NAME = 'col3') BEGIN SELECT [col3]...
'DECLARE @sql NVARCHAR(500)
SELECT @sql = ''select col1, col2, '' + case when exists(select * from INFORMATION_SCHEMA.columns where table_name = ''Table'' and column_name = ''col4'') then ''col4'' else ''null'' end + '' as res from [MyDB].[dbo].[Table]''
--print @sql
EXEC sp_executesql @sql'
) `code` (Sorry for formatting - replace
with line break.) – Moe Sisko Jan 13 '16 at 02:54