Bulk Insert several errors - bulkinsert

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?

Related

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

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'.

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

INSERT trigger causing trouble

I'm new to writing SQL Server triggers. I have a table called USERS and I also a another tabled called USERS_DELTA. The difference between the two is USERS_DELTA has one additional column called change_type.
Here are the table schema:
USERS table:
CREATE TABLE [dbo].[TDR_Users]
(
[objectGUID] [varbinary](50) NOT NULL,
[distinguishedName] [nvarchar](255) NOT NULL,
[adForest] [nvarchar](50) NULL,
[adDomain] [nvarchar](50) NULL,
[accountExpires] [datetime] NULL,
[adminCount] [int] NULL,
[cn] [nvarchar](64) NULL,
[company] [nvarchar](64) NULL,
[description] [nvarchar](448) NULL,
[displayName] [nvarchar](256) NULL,
[division] [nvarchar](256) NULL,
[employeeID] [nvarchar](16) NULL
)
And USERS_DELTA table:
CREATE TABLE [dbo].[TDR_Users]
(
[objectGUID] [varbinary](50) NOT NULL,
[distinguishedName] [nvarchar](255) NOT NULL,
[adForest] [nvarchar](50) NULL,
[adDomain] [nvarchar](50) NULL,
[accountExpires] [datetime] NULL,
[adminCount] [int] NULL,
[cn] [nvarchar](64) NULL,
[company] [nvarchar](64) NULL,
[description] [nvarchar](448) NULL,
[displayName] [nvarchar](256) NULL,
[division] [nvarchar](256) NULL,
[employeeID] [nvarchar](16) NULL,
[change_Type] [nvarchar](10) NULL
)
I have an application which will be creating records in USERS table. But what I'm trying to do is capture the inserts into the USERS_DELTA. I have written a trigger on the USERS table:
CREATE TRIGGER [dbo].[TR_INSERTS_DELTAS]
ON [dbo].[Users]
FOR INSERT
AS
DECLARE #ObjectGUID varbinary(50), #DN varchar(255), #memcount int;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Get the primary and unique keys from the inserted rows.
SELECT #DN=i.distinguishedName FROM inserted i;
SELECT #ObjectGUID = i.objectGUID FROM inserted i;
-- Check if a row already exists in the TDR_Users_Delta table with those values.
SELECT #memcount=COUNT(*) FROM Users
WHERE Users.distinguishedName = #DN
AND Users.objectGUID = #ObjectGUID ;
if(#memcount = 0)
BEGIN
INSERT INTO [dbo].[Users_Delta]
(
[objectGUID],
[distinguishedName],
[adForest],
[adDomain],
[accountExpires],
[adminCount],
[cn] ,
[company],
[description],
[displayName],
[division],
[employeeID],
[change_type]
)
VALUES
(
INSERTED.[objectGUID],
INSERTED.[distinguishedName],
INSERTED.[adForest],
INSERTED.[adDomain],
INSERTED.[accountExpires],
INSERTED.[adminCount],
INSERTED.[cn] ,
INSERTED.[company],
INSERTED.[description],
INSERTED.[displayName],
INSERTED.[division],
INSERTED.[employeeID],
'Add'
);
END
END
GO
When I execute this trigger, I get the following error:
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 94
The multi-part identifier "Inserted.objectGUID" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 95
The multi-part identifier "INSERTED.distinguishedName" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 96
The multi-part identifier "INSERTED.adForest" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 97
The multi-part identifier "INSERTED.adDomain" could not be bound.
Msg 4104, Level 16, State 1, Procedure TR_INSERTS_DELTAS, Line 98
...
What am I doing wrong? :(
I think you just need to put a select with the table in rather than using inserted.x to signify the insert.
CREATE TRIGGER [dbo].[TR_INSERTS_DELTAS]
ON [dbo].[Users]
FOR INSERT
AS
DECLARE #ObjectGUID varbinary(50), #DN varchar(255), #memcount int;
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Get the primary and unique keys from the inserted rows.
SELECT #DN=i.distinguishedName FROM inserted i;
SELECT #ObjectGUID = i.objectGUID FROM inserted i;
-- Check if a row already exists in the TDR_Users_Delta table with those values.
SELECT #memcount=COUNT(*) FROM Users
WHERE Users.distinguishedName = #DN
AND Users.objectGUID = #ObjectGUID ;
if(#memcount = 0)
BEGIN
INSERT INTO [dbo].[Users_Delta]
(
[objectGUID],
[distinguishedName],
[adForest],
[adDomain],
[accountExpires],
[adminCount],
[cn] ,
[company],
[description],
[displayName],
[division],
[employeeID],
[change_type]
)
select
INSERTED.[objectGUID],
INSERTED.[distinguishedName],
INSERTED.[adForest],
INSERTED.[adDomain],
INSERTED.[accountExpires],
INSERTED.[adminCount],
INSERTED.[cn] ,
INSERTED.[company],
INSERTED.[description],
INSERTED.[displayName],
INSERTED.[division],
INSERTED.[employeeID],
'Add'
From inserted
END
END
GO

SQL database management

I'm currently having issues with my database. It shows this error:
Msg 1911, Level 16, State 1, Line 13
Column name 'suffix_desc' does not exist in the target table or view.
Msg 1750, Level 16, State 0, Line 13
Could not create constraint. See previous errors.
This is the code,
create table prefix
(
prefix_desc varchar(4) not null,
primary key (prefix_desc)
)
create table suffix
(
suffix_desc varchar(4) not null,
primary key (suffix_desc)
)
create table member
(
member_id varchar(80) not null,
First_name varchar(50) not null,
Last_name varchar(50) not null,
middle_name varchar(50) null,
Dob date not null,
Email varchar(80) not null,
UserID varchar(80) null,
Password varchar(16) not null,
phone_friendly_ind varchar(3) not null,
SMS_ind varchar(3) not null,
return_ind varchar(3) not null,
fuel_prepay_ind varchar(3) not null,
post_mail_ind varchar(3) not null,
email_ind varchar(3) not null,
privacy_ind varchar(3) not null,
primary key (member_id, suffix_desc, prefix_desc),
foreign key (suffix_desc) references suffix (suffix_desc),
foreign key (prefix_desc) references prefix (prefix_desc)
)
I think you forgot to add this :
create table member(
...
suffix_desc varchar(4) not null,
prefix_desc varchar(4) not null,
...
)

SCOPE_IDENTITY() id's conflicts

I have a 3 tables UniversityReg, SupporterReg & Login. If university or supporter register with the system, always general details goes to their table & login details goes to Login table. In here I use scope_identity.
I'm getting error when I go to save supporter reg details.
Errors
Msg 515, Level 16, State 2, Procedure SupporterReg_SP, Line 16
Cannot insert the value NULL into column 'SupporterId', table 'CounsellingDB.dbo.SupporterReg'; column does not allow nulls. INSERT fails.
Msg 515, Level 16, State 2, Procedure SupporterReg_SP, Line 20
Cannot insert the value NULL into column 'LoginID', table 'CounsellingDB.dbo.Login'; column does not allow nulls. INSERT fails.
UniversityReg SP
ALTER PROCEDURE [dbo].[UniversityReg_SP]
(
#Username varchar(50),
#Password varchar(50),
#UniversityName varchar(50) ,
#GovernmentRegNo varchar(50) ,
#Country varchar(50) ,
#CreatedBy varchar(50)
)
AS
DECLARE #LoginID int
INSERT INTO UniversityReg (UniversityName,GovernmentRegNo,Country,CreatedBy,ShortCode)values(#UniversityName,#GovernmentRegNo,#Country,#CreatedBy,'UNI')
SET #LoginID = SCOPE_IDENTITY();
INSERT INTO Login values(#LoginID,#Username,#Password,'UNI')
RETURN
SupporterReg_SP
CREATE PROCEDURE [dbo].[SupporterReg_SP]
(
#UserName varchar(50),
#Password varchar(50),
#SupporterName varchar(50),
#University varchar(50) ,
#ContactNo varchar(50),
#Email varchar(50),
#StudentLocation varchar(50)
)
AS
DECLARE #LoginID int
INSERT INTO SupporterReg(SupporterName,University,ContactNo,Email,StudentLocation,ImagePath,ShortCode)V alues(#SupporterName,#University,#ContactNo,#Email,#StudentLocation,'','SUP')
SET #LoginID = SCOPE_IDENTITY();
INSERT INTO Login values(#LoginID,#UserName,#Password,'SUP')
RETURN
UniversityReg Table
[UniversityId] [int] IDENTITY(1,1) NOT NULL,
[Username] [varchar](50) NULL,
[Password] [varchar](50) NULL,
[UniversityName] [varchar](50) NULL,
[GovernmentRegNo] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[CreatedBy] [varchar](50) NULL,
[ShortCode] [varchar](50) NULL,
Login Table
[LoginID] [int] NOT NULL,
[UserName] [nvarchar](50) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[ShortCode] [nvarchar](50) NULL
SupporterReg table
[SupporterId] [int] NOT NULL,
[SupporterName] [varchar](50) NULL,
[University] [varchar](50) NULL,
[ContactNo] [varchar](50) NULL,
[Email] [varchar](50) NULL,
[StudentLocation] [varchar](50) NULL,
[ImagePath] [varchar](50) NULL,
[ShortCode] [varchar](50) NULL,
In your stored procedures #LoginID is the ID for SupporterReg or UniversityReg, not for Login
In Login, your LoginID column should be defined as int identity(1,1) and you should specify column names in your insert
INSERT INTO Login (column, names, go here)
values(#LoginID,#UserName,#Password,'SUP')
Your trouble is that your procedure is attempting to insert multiple values into the SupporterReg table however you are not including a value for the SupporterID column, which has been defined a NOT NULL.
You can either pass a value along with that insert statement, or adjust the table DDL so that it's an IDENTITY column and will fill that data for you.
Your design is wrong. You should not be using the id from two different tables in the login table as the loginid. This is a model that can not work in practice as both tables will sooner or later have the same id and you won't know which one the login relates to. You have a the parent child relationship reversed.
The correct design is to insert to Login first making the loginid the identity. Then insert to the child table of either UniversityReg or SupporterReg. When you do this you can have FKs and referntial integrity.