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?
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];
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With