Delete row if table exists SQL

后端 未结 9 892
旧时难觅i
旧时难觅i 2021-01-17 10:36

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 d

相关标签:
9条回答
  • 2021-01-17 10:54

    For MySQL

    show tables like "test1";
    

    For SQL Server

    SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'testSchema' AND     TABLE_NAME = 'test1'
    
    0 讨论(0)
  • 2021-01-17 10:55

    This one deletes the row and does not complain if it can't.

    DELETE IGNORE FROM table WHERE id=1
    

    source here.

    0 讨论(0)
  • 2021-01-17 11:04

    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

    0 讨论(0)
  • 2021-01-17 11:06

    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

    0 讨论(0)
  • 2021-01-17 11:06

    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
    
    0 讨论(0)
  • 2021-01-17 11:08

    For SQL Server: You could use:

    IF OBJECT_ID('tablename','U') IS NOT NULL
    
    0 讨论(0)
提交回复
热议问题