For example. I have a database upgrade script for adding a column to a database table. It looks a little like this:
IF NOT Exists(SELECT * FROM SysColumns sc, SysObjects so
WHERE sc.Name = 'dealer_number'
AND so.Name = 'collector'
AND so.Type= 'U'
AND so.id = sc.id)
BEGIN
-- SQL for creating column
END
ELSE
BEGIN
-- notify user that column already exists
END
How do I notify the user that the column already exists?
RAISERROR ('column already exists',0,1) with nowait
or
print 'column already exists'
you can use PRINT statement in SQL
RAISERROR seems appropriate here. See here.
Use PRINT - it works from most SQL client applications. SELECT also works
e.g
PRINT 'column already exists or something'
or
SELECT 'column already exists or something'
Related
I am using SQL Server 2008 R2. I have created some SQL statements for some migration:
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TableA' AND COLUMN_NAME='Status')
BEGIN
UPDATE TableA
SET Status = 'Active'
WHERE Status IS NULL
END
Now, I have dropped the column Status from database table TableA.
Again when I am executing the above block, and although I have placed a check whether that column exists, only then it should execute the UPDATE statement, it gives me error
Invalid column name 'Status'
How to get rid of this error?
Thanks
You need to put the code to run in a separate scope/batch:
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='TableA' AND COLUMN_NAME='Status')
BEGIN
EXEC('UPDATE TableA SET Status=''Active'' WHERE Status IS NULL')
END
The problem you currently have is that the system wants to compile your batch of code before it executes any part of it. It can't compile the UPDATE statement since there's a column missing, so it never even has a chance to start executing the code and considering whether the EXISTS predicate returns true or false.
Your current SQL Block might fail some times because Information_schema is view and not a table. Also, according to MSDN
Some changes have been made to the information schema views that break backward compatibility.
Hence we can't rely on information schema views.
Instead use sys.tables
IF EXISTS(SELECT 1 FROM SYS.COLUMNS
WHERE NAME = N'Status' AND OBJECT_ID = OBJECT_ID(N'TableA'))
BEGIN
UPDATE TableA SET Status='Active' WHERE Status IS NULL
END
I've been trying to write this simple mysql statement to check if a table exists:
IF object_id('carpool'.'users', 'U') is not null THEN
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
END IF
'carpool' is my schema and 'users' is a table
My sql version is 5.1.52-community
I keep getting this error:
Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF' at line 1 0.000 sec
I've tried several syntaxes such as IF BEGIN END ELSE BEGIN END to no avail.
any ideas?
It looks like you're trying to do a form of T-SQL, which MySQL does not support.
There is no print function, nor object_id. There is a form of IF function that can be used in a SELECT statement:
SELECT IF(1 = 1, 'present', 'not');
Are you reading MSSQL doco instead of MySQL doco? MSSQL supports these functions.
Depending on what you are after, you might want to use something like this:
SELECT
CASE WHEN EXISTS (SELECT NULL
FROM information_schema.tables
WHERE table_schema = 'carpool' AND table_name = 'users')
THEN 'Present'
ELSE 'Not accounted for' END;
This will check if table users exists in carpool schema. Please see example here.
Every statement must be terminated by semicolon.
Like this
IF object_id('carpool'.'users', 'U') is not null THEN
PRINT 'Present!';
ELSE
PRINT 'Not accounted for';
END IF;
Quick question. I am currently using INSERT... SELECT statement to check a user has a basic member account before they become a coach. This code works fine:
INSERT into coaches (U_Name, P_word, M_ID)
SELECT members.U_Name,members.P_word,members.M_ID FROM members
WHERE members.U_Name="bob1" AND members.P_word="123"
ON DUPLICATE KEY UPDATE U_Name = members.U_Name, P_word = members.P_word;
As you can see I am currently just updating their account with the same data if they already exist. What I want to do now is if the user is a member and has already become a coach, to display a message informing them they are already registered as a coach.
So my question is, do I wrap this in an IF... ELSE statement or do I use an IF EXISTS statement such as this insert if not exists else just select in mysql
Was thinking along the lines of:
IF EXISTS(SELECT coaches.U_Name,coaches.P_word,coaches.M_ID FROM coaches
WHERE coaches.U_Name="bob1" AND coaches.P_word="123")
ELSE
BEGIN
INSERT into coaches (U_Name, P_word, M_ID)
SELECT members.U_Name,members.P_word,members.M_ID FROM members
WHERE members.U_Name="bob1" AND members.P_word="123"
END;
Have also looked at this example here: MySql IF exists select ELSE insert but not sure how I would implement it. Any instructions on where to go from here would be appreciated.
INSERT ... ON DUPLICATE KEY UPDATE Syntax can help you on resolving the issue.
It is available starting on mySQL 5.0
Reference: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
I have a script that drops a load of tables using DROP TABLE IF EXISTS, this works.
There is also a delete in this script to DELETE a row from another table that I do not manage. This table may or may not exist.Is there any to check the table exists before attempting to delete a row?
this needs to work for MYSQL and SQLServer
thanks
Alex
To check in SQL SERVER,
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
To check in mysql:
You simply count:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
This one deletes the row and does not complain if it can't.
DELETE IGNORE FROM table WHERE id=1
source here.
For SQL Server: You could use:
IF OBJECT_ID('tablename','U') IS NOT NULL
I dont think you'll find a common syntax between SQL server and my SQL. I mean, you can check if the table exsits on SQL Server using something like:
if exists(select * from sys.objects where name like 'table_name')
but mySql would have its own catalog.
Unless you write a script like:
if (sql_server) then
if exists(select * from sys.objects where name like 'table_name')
else --mySQl
--execute the mysql script
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TABLE_NAME]') AND type in (N'U'))
It seems to me right the first item in the "Related" column on the right side answers your question.... Check if table exists in SQL Server
For MySQL
show tables like "test1";
For SQL Server
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'testSchema' AND TABLE_NAME = 'test1'
A question you want to ask yourself (in terms of database design): Why are you trying to delete rows from a table you are not sure exists? If it doesn't, but you expect it does, wouldn't you rather create the table than not delete it?
Anyway, Chris Gesslers answer does exactly what you are asking in SQL Server, but there is some smell here.
The construct in MySQL you can use is
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'tablename'
and check for results
you can use bellow code:
DECLARE #TABLENAME VARCHAR(20)='TableName';
IF (OBJECT_ID(#TABLENAME) IS NOT NULL )
BEGIN
execute(N'TRUNCATE TABLE ' + #TABLENAME + '' );
END
ELSE
BEGIN
PRINT 'Table NOT Exists'
END
How could I want to add a column if not exist.
I tried this code:
IF EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'forwind.measuringdata_fino_10_00000000'
AND table_schema = 'forwind'
AND column_name != 'F1_USA(40)_u') THEN
ALTER TABLE `forwind.measuringdata_fino_10_00000000` ADD `F1_USA(40)_u` FLOAT NOT NULL default '0';
END IF;
but I get the following error:
Error Code: 1064 You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'IF EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
Good for me if somebody know an other solution!
MySQL does not support anonymous IF statements like that.
You have at least 3 options to address this:
1) Just run the ALTER TABLE statement and ignore the Duplicate column name error if the column already exists. If you're executing a bunch of DDL in a script you can use mysql -f to ignore the errors and keep going.
2) Use a scripting language such as bash, python, perl etc to check for the existence of the column and then add it if it does not already exist.
3) Create a stored procedure in MySQL to check for the existence of the column and then add it if it does not already exist.
P.S. As an aside, I recommend against putting parentheses in column names, because that forces you to quote the column name every time you reference it.
------Add an IpAddress column in ActionsTracking table if -----
DECLARE #tableName varchar(MAX) ='ActionsTracking'
DECLARE #columnName varchar(MAX) ='IpAddress'
IF EXISTS(SELECT 1 FROM sys.columns
WHERE Name = #columnName
AND Object_ID = Object_ID(#tableName))
PRINT 'Column Already Exists'
ELSE
BEGIN
EXEC('ALTER TABLE '+#tableName+'
ADD '+ #columnName +' varchar(15) null')
PRINT 'Column Added Sucessfully'
END