Msg 156, Level 15, State 1, Line 21 Incorrect syntax near the keyword 'create' - sql

USE master;
GO
CREATE DATABASE Sales
ON
(NAME= Sales_Data,
FILENAME = 'F:\\DB\\Customer DB\\Sales_Data.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5)
LOG ON
(NAME = Sales_Log,
FILENAME = 'F:\\DB\\Customer DB\\Sales_Log.ldf',
SIZE = 5,
MAXSIZE= 25,
FILEGROWTH = 5);
GO
USE Sales;
GO
CREATE SCHEMA Sales_schema;
CREATE SCHEMA Production;
USE Sales;
GO
CREATE TABLE Sales.sales.customers
(
customer_id int,
first_name varchar (15) NOT NULL,
last_name varchar (15) NOT NULL,
email_address varchar (50) NOT NULL,
phone varchar (15),
state varchar (15),
city varchar (15) NOT NULL,
street varchar (30) NOT NULL,
zip_code varchar (5) NOT NULL,
CONSTRAINT customers_uq UNIQUE KEY (phone),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
CREATE TABLE Production.categories
(
category_id INT PRIMARY KEY,
category_name VARCHAR (20)
);
CREATE TABLE Production.brands
(
brand_id INT,
brand_name VARCHAR (20),
CONSTRAINT brands_pk PRIMARY KEY (brand_id)
);
I expected no errors at all, but I found multiple errors. Please check these unexpected errors
Msg 156, Level 15, State 1, Line 21
Incorrect syntax near the keyword 'create'.
Msg 1801, Level 16, State 3, Line 26
Database 'SALES' already exists. Choose a different database name.
Msg 156, Level 15, State 1, Line 46
Incorrect syntax near the keyword 'CREATE'.
Msg 156, Level 15, State 1, Line 63
Incorrect syntax near the keyword 'key'.

Related

Error inserting date into date type column

create table DogLicense ( License int IDENTITY(1,1) PRIMARY KEY, Expires date NOT NULL CHECK(Expires > '1990-01-01') , Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF')), PetName char(50) NOT NULL , Breed char(50) , OwnerLastName char(50) NOT NULL , OwnerFirstName char(50) NOT NULL , Address char(50) , Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212), Phone char(10) , )
So I have created the table above and when attempting to enter my first row of data I get the error
Msg 241, Level 16, State 1, Line 1 Conversion failed when converting date and/or time from character string.
My insert into statement is as follows. From everything I have read so far I'm using the correct format. Any idea why this isn't working?
insert into DogLicense values ('2023-21-06','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )
I have tried not using quotes but I get
`Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date'
SQL Server likes his date in yyyymmdd as string to be inserted
create table DogLicense
( License int IDENTITY(1,1) PRIMARY KEY
, Expires date NOT NULL CHECK(Expires > '1990-01-01')
, Sex char(2) NOT NULL CONSTRAINT check_Sex_M_F_NM_SF CHECK (Sex IN ('M','F','NM','SF'))
, PetName char(50) NOT NULL
, Breed char(50)
, OwnerLastName char(50) NOT NULL
, OwnerFirstName char(50) NOT NULL
, Address char(50)
, Zip Char(5) NOT NULL CHECK(Zip >= 99201 and zip <= 99212)
, Phone char(10) )
insert into DogLicense values
('20230621'
,'NM'
, 'Rosco'
, 'St. Bernard'
,'Freeman','Mark'
, '123 Medow Ln.'
,'99207'
,'5095551212' )
1 rows affected
fiddle
I believe you are trying to insert the date as YYYY-DD-MM instead of YYYY-MM-DD.
Try
insert into DogLicense values ('2023-06-21','NM', 'Rosco', 'St. Bernard','Freeman','Mark', '123 Medow Ln.','99207','5095551212' )

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.
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
Use single quotes (') instead of double quotes (")
Remove the quotes from the identifiers (DatabaseName, TableName)
Replace the quotes in the column names with square brackets ([])
IF NOT EXISTS
(
SELECT 1
FROM [master].sys.databases
WHERE [name] = 'mjDB'
)
BEGIN CREATE DATABASE mjDB; END
GO
USE mjDB;
GO
-- Dumping structure for table mjDB.PushNotificationLog
IF (OBJECT_ID('dbo.PushNotificationLog', 'U') IS NULL)
BEGIN
CREATE TABLE dbo.PushNotificationLog
(
[PushNotificationLogID] INT NOT NULL
, [ItemType] VARCHAR(20)
, [ItemID] INT
, [ServicemanID] INT
, [Title] VARCHAR(100)
, [Body] VARCHAR(4000)
, [TranId] INT
, [CreatedBy] INT
, [CreatedDate] DATETIME
, CONSTRAINT PK__PushNotificationLog PRIMARY KEY ([pushNotificationLogId])
);
END
GO

Bulk Insert several errors

Im trying to upload 1000 txt files into one table un SQL. I'm using the following query, to upload one txt file at a time:
CREATE TABLE [dbo].test1
(
[Division] varchar(50) null,
[Factura] varchar(50) null,
[Fecha Factura] varchar(50) null,
[Inicio Período] varchar(50) null,
[Fin Período] varchar(50) null,
[Tipo de Factura] varchar(50) null,
[Cuenta Contrato] varchar(50) null,
[Tipo de Cliente] varchar(50) null,
[Servicio Facturado] varchar(50) null,
[Porción] varchar(50) null,
[Unidad de Lectura] varchar(50) null,
[Tipo de Consumo] varchar(50) null,
[Concepto Facturado] varchar(50) null,
[Consumo Facturado] varchar(50) null,
[Importe Facturado] varchar(50) null,
[Importe CCAR] varchar(50) null
)
BULK INSERT [dbo].test1
FROM '\\dataserver\SQL Data Files\SQL_EMELIZ\FC x Bloque Detallada\201308 Detalle Facturas\FACT_BLOQ_AGO13 (1).txt'
WITH
(
FIELDTERMINATOR = ';',
ROWTERMINATOR = '0x0A'
)
but gives this error message:
Msg 4832, Level 16, State 1, Line 22 Bulk load: An unexpected end of
file was encountered in the data file. Msg 7399, Level 16, State 1,
Line 22 The OLE DB provider "BULK" for linked server "(null)" reported
an error. The provider did not give any information about the error.
Msg 7330, Level 16, State 2, Line 22 Cannot fetch a row from OLE DB
provider "BULK" for linked server "(null)".
Can anyone help me?

Error in creating tables in SQL

I'm trying to create a few tables in a new database, but when I try to create them it creates a couple of errors. I'm currently using Microsoft SQL Server Management Studio.
The errors seem to be in the end of the code where I'm trying to add constraints for foreign keys. Any help would be greatly appreciated thank you.
Here's the code, it's meant to generate 3 tables with 1 table containing 2 foreign keys to the other tables with matching column names.
CREATE TABLE Customers
(
CustomerID INT NOT NULL PRIMARY KEY IDENTITY,
ContactName VarChar(50) NULL,
Company VarChar(45) NULL,
Phone VarChar(12) NULL,
)
CREATE TABLE Shippers
(
ShipperID INT NOT NULL PRIMARY KEY IDENTITY,
Company VarChar(45) NULL,
Phone VarChar(12) NULL,
)
CREATE TABLE Orders
(
OrderID INT NOT NULL PRIMARY KEY IDENTITY,
OrderDate DATETIME NULL,
ShippedDate DATETIME NULL,
ShipperID INT NULL,
Freight DECIMAL NULL,
CustomerID INT NULL,
CONSTRAINT fk_Orders_Shippers
FOREIGN KEY ShipperID
REFERENCES Shippers(ShipperID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
CONSTRAINT fk_Orders_Customers
FOREIGN KEY CustomerID
REFERENCES Customers(CustomerID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
And these are the errors I get:
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near 'ShipperID'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'ACTION'.
Msg 102, Level 15, State 1, Line 28
Incorrect syntax near 'ACTION'.
Any ideas what the problem is?
The error messages point you to a couple of surplus commas, a missing comma and improper foreign key syntax due to missing parentheses.
This is the correct version:
CREATE TABLE Customers (
CustomerID INT NOT NULL PRIMARY KEY IDENTITY,
ContactName VarChar(50) NULL,
Company VarChar(45) NULL,
Phone VarChar(12) NULL -- SURPLUS COMMA REMOVED
)
CREATE TABLE Shippers (
ShipperID INT NOT NULL PRIMARY KEY IDENTITY,
Company VarChar(45) NULL,
Phone VarChar(12) NULL -- SURPLUS COMMA REMOVED
)
CREATE TABLE Orders (
OrderID INT NOT NULL PRIMARY KEY IDENTITY,
OrderDate DATETIME NULL,
ShippedDate DATETIME NULL,
ShipperID INT NULL,
Freight DECIMAL NULL,
CustomerID INT NULL,
CONSTRAINT fk_Orders_Shippers
FOREIGN KEY (ShipperID) -- PARENTHESES ADDED
REFERENCES Shippers(ShipperID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
, -- COMMA ADDED
CONSTRAINT fk_Orders_Customers
FOREIGN KEY (CustomerID) -- PARENTHESES ADDED
REFERENCES Customers(CustomerID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)

Microsoft SQL Server - check constraint error when using stored procedure (msg 547)

I keep getting the following error:
Msg 547, Level 16, State 0, Procedure add_new_customer, Line 6
The INSERT statement conflicted with the CHECK constraint "CK__customer__addres__09A971A2". The conflict occurred in database "AIT 732 - Bank", table "dbo.customer", column 'address_state'.
The following is table that I am attempting to update:
create table customer
(
cust_id numeric(10,0) not null identity primary key,
social_security_num numeric(9,0) not null,
first_name varchar(20) not null,
last_name varchar(20) not null,
primary_address varchar(50) not null,
address_zip_code numeric(5,0) not null,
address_state char(2) check (address_state in('md','pa','dc', 'de', 'wv', 'va','nj')),
gender char(1) not null check (gender in('m','f')),
phone_num numeric(10,0) null
)
this is the stored procedure i created:
create procedure add_new_customer
(#social_sec numeric, #f_name varchar, #l_name varchar, #pri_address varchar, #zip numeric, #add_state char, #gender char, #phone numeric)
as
begin
begin transaction
insert into customer(
social_security_num,
first_name,
last_name,
primary_address,
address_zip_code,
address_state,
gender,
phone_num)
values (
#social_sec,
lower(#f_name),
lower(#l_name),
lower(#pri_address),
#zip,
lower(#add_state),
lower(#gender),
#phone)
if ##ERROR != 0
begin
rollback transaction
return ##error
end
commit transaction
end
and last but not least, this is how I am calling procedure
add_new_customer 211118888, 'Bob', 'JONES', '222 some st', 21333, 'md', 'm', 4102227878
I've been messing with this for about and hour and can not figure out where that error is coming from. any help would be appreciated.
Your stored proc parameter definition is #add_state char but this will truncate your input value of 'md' to 'm' which isn't a valid value. Change you parameter definition to match the table defn char(2) and it should then work.