Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Insert depending if a column exists

Tags:

I need to do one INSERT or another depending if a column exist because of different versions of the same table.

I did the approach at this thread but SQL Server's pre check or 'sort of compilation' detects an error that would not fail during execution time.

Here's some code

IF COL_LENGTH('TableA', 'Column2') IS NOT NULL BEGIN  INSERT INTO [dbo].[TableA]([Column1], [Column2], [Column3], [Column4]) SELECT value1, value2, value3, value4  END ELSE BEGIN  INSERT INTO [dbo].[TableA]([Column1], [Column3], [Column4]) SELECT value1, value3, value4  END 

Any workaround?

like image 782
framara Avatar asked Aug 21 '13 09:08

framara


People also ask

How do you check if a column exists or not in SQL?

Colum view to check the existence of column Name in table SampleTable. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE table_name = 'SampleTable' AND column_name = 'Name' ) SELECT 'Column exists in table' AS [Status] ; ELSE SELECT 'Column does not exist in table' AS [Status];

How do you insert if not exists?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.

How do you check if a column exists in multiple tables in SQL?

The easiest and straightforward way to check for the column in a table is to use the information schema for column system view. Wright a select query for INFORMATION_SCHEMA. COLUMNS as shown below. If the query returns record, then the column is available in the table.


1 Answers

SQL will know that the column doesn't exist so it won't let you run the query. The solution would be to execute a dynamic query.

DECLARE @value1 AS VARCHAR(50) DECLARE @value2 AS VARCHAR(50) DECLARE @value3 AS VARCHAR(50) DECLARE @value4 AS VARCHAR(50)  SET @value1 = 'somevalue1' SET @value2 = 'somevalue2' SET @value3 = 'somevalue3' SET @value4 = 'somevalue4'  DECLARE @SQL AS VARCHAR(MAX)  IF COL_LENGTH('TableA', 'Column2') IS NOT NULL     BEGIN          SET @SQL =              'INSERT INTO [dbo].[TableA]([Column1], [Column2], [Column3], [Column4])             SELECT ' + @value1 + ', ' + @value2 + ', ' + @value3 + ', ' + @value4      END  ELSE     BEGIN          SET @SQL =              'INSERT INTO [dbo].[TableA]([Column1], [Column3], [Column4])             SELECT ' + @value1 + ', ' + @value3 + ', ' + @value4      END  EXEC(@SQL) 
like image 184
Giannis Paraskevopoulos Avatar answered Oct 01 '22 18:10

Giannis Paraskevopoulos