检查$ tablename在SQL Server 2017中是否存在,如果不存在则创建表$ tablename

时间:2019-12-14 13:55:23

标签: php sql-server pdo odbc sqlsrv

我想检查SQL Server 2017表$ tablename(由用户以PHP形式输入)是否存在:

    try {
        $dothis = "
            IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N$tablename)
               CREATE TABLE $tablename ( id int IDENTITY (1,1), Name text, GeomCol1 geometry, GeomCol2 AS GeomCol1.STAsText() )";
        $tbl = $pdo->exec($dothis);
    } catch(PDOException $e) {
        echo "Error: ".$e->getMessage();
    }

但是我总是得到相同的错误:

SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'NNewTable'.

这里:

    try {
        $dothis = "
            IF OBJECT_ID ( $tablename, 'U' ) IS NULL 
            BEGIN 
               CREATE TABLE $tablename ( id int IDENTITY (1,1), Name text, GeomCol1 geometry, GeomCol2 AS GeomCol1.STAsText() )
            END";
        $tbl = $pdo->exec($dothis);

错误:

SQLSTATE[42S22]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'NewTable'.

如果我不检查表是否首先存在,则创建表没有问题:

    try {
        $dothis = "
               CREATE TABLE $tablename ( id int IDENTITY (1,1), Name text, GeomCol1 geometry, GeomCol2 AS GeomCol1.STAsText() )";
        $tbl = $pdo->exec($dothis);
    } catch(PDOException $e) {
        echo "Error: ".$e->getMessage();
    }

没有错误,它将创建名称为$ tablename的表

我发现check if a table exists in SQL Server

有很多不同的方法

不幸的是,每次我尝试使用$ tablename变量来检查表是否存在时,它都会返回错误。我希望有人能提供帮助。

2 个答案:

答案 0 :(得分:2)

用作文字时,将表名括在单引号中。另外,如果表名可能不符合rules for regular identifiers(例如,嵌入的空格),请考虑将表名括在方括号(或双引号)中。

try {
    $dothis = "
        IF OBJECT_ID ( N'$tablename', 'U' ) IS NULL 
        BEGIN 
           CREATE TABLE [$tablename] ( id int IDENTITY (1,1), Name text, GeomCol1 geometry, GeomCol2 AS GeomCol1.STAsText() )
        END";
    $tbl = $pdo->exec($dothis);

答案 1 :(得分:0)

这也有效:

    try {
        $dothis = "
            if not exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = N'$tablename')
            BEGIN 
               CREATE TABLE $tablename ( id int IDENTITY (1,1), Name text, GeomCol1 geometry, GeomCol2 AS GeomCol1.STAsText() )
            END";
        $tbl = $pdo->exec($dothis);