sql检查sql数据库中是否存在表

ttisahbt  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(288)

我正在努力检查数据库中是否存在表。到目前为止,我所做的工作如下:

public boolean isTableExist(String tableName) {
    JdbcTemplate jdbc = getJdbcTemplate();
    String query =
        "IF (OBJECT_ID(?) IS NOT NULL ) "
            + "BEGIN "
            + "  PRINT 1 "
            + "  RETURN "
            + "END "
            + "ELSE "
            + "BEGIN "
            + "  PRINT 0 "
            + "  RETURN "
            + "END";

    Integer result = jdbc.queryForObject(query, Integer.class, tableName);
    return result == 1 ? true : false;
  }

输出(错误):
preparedstatementcallback;sql的未分类sqlexception[如果(object\u id(?)不为空)begin print 1 return end else begin
打印0返回结束];sql状态[null];错误代码[0];语句没有返回结果集。;嵌套异常为com.microsoft.sqlserver.jdbc.sqlserverexception:语句未返回结果集。

bvk5enib

bvk5enib1#

也可以运行如下查询:

select count(*)
from information_schema.tables
where table_name = 'yourtablename'
    -- optionally this too
    -- and table_schema = 'dbo';

如果得到0,表就不存在。
基于jdbctemplate count queryforint和pass multiple parameters answer,在存储查询之后,似乎必须使用类似的方法

jdbc.queryForObject(
    "select count(*) from information_schema.tables where table_name = ?"
    , new Object[] { tableName }
    , Integer.class
);

更新:在本帖的帮助下,问题已经解决,基于以上信息的最终解决方案是:

String query =
        "select count(*) "
            + "from information_schema.tables "
            + "where table_name = ? and table_schema = 'dbo'";
    Integer result = jdbc.queryForObject(query, Integer.class, tableName);

相关问题