SQL删除以公共前缀开头的表

时间:2019-03-22 09:29:40

标签: mysql sql database

我希望编写一个SQL查询/存储过程,该程序将删除数据库中以“ table”之类的通用前缀开头的表。

但是,表名以前缀开头,后跟数字,如果可以将表号附加到前缀,则我不想删除所有表名。

谢谢

3 个答案:

答案 0 :(得分:1)

看看这个: Get table names using SELECT statement in MySQL

您可以将该表加入表前缀的约束

希望能带来帮助并带来乐趣

答案 1 :(得分:1)

在所有表中查找列,如:

SELECT      c.name  AS 'ColumnName'
            ,t.name AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       c.name LIKE '%SubId%'
ORDER BY    TableName
            ,ColumnName;

查找所有表名称如下的表:

SELECT      c.name  AS 'ColumnName'
            ,t.name AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       t.name LIKE '%tbl%'
ORDER BY    TableName
            ,ColumnName;

查找特定模式中的所有表:

SELECT t.name 
  FROM sys.tables AS t
  INNER JOIN sys.schemas AS s
  ON t.[schema_id] = s.[schema_id]
  WHERE s.name = N'cmc';

一旦有了需要删除的表,就可以为每个表编写delete语句。或者您可以使用类似以下的内容:

SELECT      c.name  AS 'ColumnName'
            ,t.name AS 'TableName',
            'drop table ' + t.name
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       t.name LIKE '%tbl%'
ORDER BY    TableName
            ,ColumnName;

编辑

在select语句下面,其中详细介绍了where子句:

SELECT      c.name  AS 'ColumnName'
            ,t.name AS 'TableName'          
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       
            t.name LIKE 'tbl%' -- where the table name starts with the letters 'tbl'
            OR t.name LIKE 'tbl%123%' -- where the table name starts with the letters 'tbl' and has the numbers '123' in the table name
            OR c.name LIKE '%colName%' -- where a column has a name that contains the letters 'colName'

ORDER BY    TableName
            ,ColumnName;

答案 2 :(得分:1)

找到所有以前缀开头的表名,并动态创建删除查询,然后将结果插入到 temp 表中,如下所示:

html, body { height: 100%}

在临时表上写入光标,并使用 sp_executesql 来执行这样的放置查询。

DECLARE @YourPrefix VARCHAR(MAX) = 'table'
SELECT    
    'DROP TABLE ' + t.name AS DropQuery
INTO #TMP
FROM        
      sys.tables  t   
WHERE
    t.name LIKE @YourPrefix + '%'

它会删除所有以您的前缀开头的表。