Search code examples
sqlsql-serverheidisql

Msg 156, Level 15, State 1, Line 16 Incorrect syntax near the keyword 'IF'


-- --------------------------------------------------------
-- Host:                         192.168.62.245
-- Server version:               Microsoft SQL Server 2014 - 12.0.2000.8
-- Server OS:                    Windows NT 6.1 <X64> (Build 7601: ) (WOW64) (Hypervisor)
-- HeidiSQL Version:             9.5.0.5196
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES  */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;


-- Dumping database structure for mjDB
CREATE DATABASE IF NOT EXISTS "mjDB";
USE "mjDB";

-- Dumping structure for table mjDB.PushNotificationLog
CREATE TABLE IF NOT EXISTS "PushNotificationLog" (
    "pushNotificationLogId" INT(10,0) NOT NULL,
    "itemType" VARCHAR(20) NULL DEFAULT NULL,
    "itemId" INT(10,0) NULL DEFAULT NULL,
    "servicemanId" INT(10,0) NULL DEFAULT NULL,
    "title" VARCHAR(100) NULL DEFAULT NULL,
    "body" VARCHAR(4000) NULL DEFAULT NULL,
    "tranId" INT(10,0) NULL DEFAULT NULL,
    "createdBy" INT(10,0) NULL DEFAULT NULL,
    "createdDate" DATETIME(3) NULL DEFAULT NULL,
    PRIMARY KEY ("pushNotificationLogId")
);

I exported this one from HeidiSQL updated to 19/12/2017, when I try to run this on SQL Server 2014 I get this error:

Msg 156, Level 15, State 1, Line 16
Incorrect syntax near the keyword 'IF'.

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near 'mjDB'.

Msg 911, Level 16, State 1, Line 17
Database 'mjDB' does not exist. Make sure that the name is entered correctly.


Solution

  • Your create table syntax is wrong if you are using SQL Server. Change the code like this if you wish to check the table existence before creating

    IF object_id('PushNotificationLog') IS NULL
    BEGIN
         CREATE TABLE [PushNotificationLog] 
         (
             pushNotificationLogId INT NOT NULL,
             itemType VARCHAR(20) NULL DEFAULT NULL,
             itemId INT NULL DEFAULT NULL,
             servicemanId INT NULL DEFAULT NULL,
             title VARCHAR(100) NULL DEFAULT NULL,
             body VARCHAR(4000) NULL DEFAULT NULL,
             tranId INT NULL DEFAULT NULL,
             createdBy INT NULL DEFAULT NULL,
             createdDate DATETIME NULL DEFAULT NULL,
    
             PRIMARY KEY (pushNotificationLogId)
        );
    END
    

    You can also do the check by checking the existence in the view sys.tables

    IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE name = 'PushNotificationLog')
    BEGIN
    
    END
    

    Similarly Check in the master.sys.databases table for the existence of Database

    IF NOT EXISTS(SELECT 1 FROM master.sys.databases WHERE name = 'mjDB')
        BEGIN
    
        END