Check if Column Exists in Database Table in SQL Server

Last Reply 3 months ago By pandeyism

Posted 3 months ago

I have a dynamic sql that works fine when the name of the columns exists, how can I make it not send error if the column does not exist

DECLARE @codigo NVARCHAR(200) 
DECLARE @column NVARCHAR(200)
SET @codigo = '110201'
SET @column = '[1]'
DECLARE @sqlQuery NVARCHAR(MAX);
SET @sqlQuery = N'SELECT '+ @column + ' FROM Codigo_Obra_Tipo_Actividad WHERE ' + @column + ' = ''' + @codigo + ''''
EXEC (@sqlQuery)

 

Posted 3 months ago

Hey NerakSeven,

Please refer below query.

SQL

CREATE TABLE TesCode(A1 VARCHAR(200))
INSERT INTO TesCode VALUES('110201')
DECLARE @codigo NVARCHAR(200)
DECLARE @column NVARCHAR(200)
SET @codigo = '110201'
SET @column = 'A1'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TesCode' AND COLUMN_NAME = @column)
BEGIN
	DECLARE @sqlQuery NVARCHAR(MAX);
	SET @sqlQuery = N'SELECT '+ @column + ' FROM TesCode WHERE ' + @column + ' = ''' + @codigo + ''''
	EXEC (@sqlQuery)
END