I have added a compute column, but I get an error when I insert the values, I left out the column name where the compute column is. I read somewhere that you don't include it in your insert.
Msg 110, Level 15, State 1, Line 641 There are fewer columns in the
INSERT statement than values specified in the VALUES clause. The
number of values in the VALUES clause must match the number of columns
specified in the INSERT statement.
CREATE TABLE Voorwerp (
voorwerpnummer BIGINT IDENTITY(30068720558,1)
NOT NULL,
titel VARCHAR(100)
NOT NULL,
beschrijving VARCHAR(max)
NOT NULL,
Startprijs NUMERIC(10,2)
NOT NULL,
Betalingswijze VARCHAR(20)
NOT NULL,
betalinginstructie VARCHAR(80)
NULL,
plaatsnaam VARCHAR(28)
NOT NULL,
Land VARCHAR(35)
NOT NULL,
Looptijd TINYINT DEFAULT ((7))
NOT NULL,
LooptijdbeginDag DATE
NOT NULL,
LooptijdbeginTijdstip TIME
NOT NULL,
Verzendkosten NUMERIC (8,2)
NULL,
verzendinstructies VARCHAR (125)
NULL,
Verkoper VARCHAR (255)
NOT NULL,
Koper VARCHAR (255)
NULL,
LooptijdeindeDag AS DATEADD(DAY,Looptijd,looptijdbeginDag),
looptijdeindeTijdstip TIME
NOT NULL,
VeilingGesloten BIT
NOT NULL,
Verkoopprijs NUMERIC(10,2)
NULL,
INSERT INTO Voorwerp(
[titel],
[beschrijving],
[Startprijs],
[Betalingswijze],
[betalinginstructie],
[plaatsnaam],
[Land],
[Looptijd],
[LooptijdbeginDag],
[LooptijdbeginTijdstip],
[Verzendkosten],
[verzendinstructies],
[Verkoper],
[Koper],
[LooptijdeindeDag],
[looptijdeindeTijdstip],
[VeilingGesloten])
VALUES('Stabiele drum/pi..',
'Stabiele drum/pi..',
50.00,
'Bank',
'Overschrijving moet...',
'New Vennep',
'Nederland',
7,
'2005-05-19',
'09:10:00',
3.50,
'Paket post binnen Nederland',
'Bianca77',
1,
'2005-05-26',
'09:30:00',
1,
500
);
Column LooptijdeindeDag is listed in the column list in the INSERT statement.
You need to remove it and it's corresponding value from the insert statement.
Your insert statement should looks like:
INSERT INTO Voorwerp(
[titel],
[beschrijving],
[Startprijs],
[Betalingswijze],
[betalinginstructie],
[plaatsnaam],
[Land],
[Looptijd],
[LooptijdbeginDag],
[LooptijdbeginTijdstip],
[Verzendkosten],
[verzendinstructies],
[Verkoper],
[Koper],
[looptijdeindeTijdstip],
[VeilingGesloten])
Related
I have a table I'm creating for an app I'm making and want to populate a calculated column from an IF statement,I don't know how to write the T-SQL for it and have looked for an answer but can't find
What i'm looking for is basically
IF (Close<=Open)
[CloseLessEqualToOpen == Yes]
ELSE
[CloseLessEqualToOpen == No]
T-SQL
CREATE TABLE [dbo].[LowFloatStocks] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Date] DATE NOT NULL,
[Ticker] NCHAR (10) NOT NULL,
[PreviousClose] DECIMAL (4, 2) DEFAULT ((4.00)) NOT NULL,
[OpeningPrice] DECIMAL (18, 2) NOT NULL,
[GainPercent] AS (round(([High]-[OpeningPrice])/[OpeningPrice],(4))*(100.0)) PERSISTED NOT NULL,
[GapPercent] AS (round(([OpeningPrice]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[Spike] DECIMAL (18, 2) NOT NULL,
[1stSpike%] AS (round(([Spike]-[OpeningPrice])/[OpeningPrice],(4))*(100.0)) PERSISTED NOT NULL,
[High] DECIMAL (18, 2) NOT NULL,
[HighPercent] AS (round(([High]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[Low] DECIMAL (18, 2) NOT NULL,
[LowPercent] AS (round(([Low]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[Close] DECIMAL (18, 2) DEFAULT ((4)) NOT NULL,
[ClosePercent] AS (round(([Close]-[PreviousClose])/[PreviousClose],(4))*(100.0)) PERSISTED NOT NULL,
[CloseLessEqualToOpen] NCHAR (3) NULL,
[CloseRed] NCHAR (3) NULL,
[ClosevHigh] AS (round(([High]-[Close])/[Close],(4))*(100)) PERSISTED NOT NULL,
[ClosevOpen] AS (round(([OpeningPrice]-[Close])/[OpeningPrice],(4))*(100.0)) PERSISTED NOT NULL,
[Catalyst] NVARCHAR (50) NOT NULL,
[Float] DECIMAL (18, 3) NOT NULL,
[Dilution] NCHAR (3) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
First of all, you need to get a single value to use in your statement:
DECLARE #Close DECIMAL (18, 2);
SET #Close = (SELECT TOP 1 Close FROM [dbo].[LowFloatStocks]);
For above statement, you can also apply WHERE or any other clause based on your need.
Then use SQL IF statement to do your comparisons, this way:
IF(#Close <= Open) -- assuming that Open is declared somewhere else
BEGIN
-- Your logic here
PRINT #Close
END
ELSE
BEGIN
-- Your logic here
PRINT #Close
END
Later you can update your Table this way:
UPDATE
[dbo].[LowFloatStocks]
SET
CloseLessEqualToOpen = ...
WHERE
...
However, there is also a more elegant solution in case if you want to make the calculation process happen automatically.
For that reason you can use Computed Columns:
CREATE TABLE [dbo].[LowFloatStocks]
(
[Close] DECIMAL (18, 2) DEFAULT ((4)) NOT NULL,
[Open] DECIMAL (18, 2) DEFAULT ((4)) NOT NULL,
-- other columns declaration here
[CloseLessEqualToOpen] AS CAST
(
CASE WHEN [Close] <= [Open] THEN 'Yes' ELSE 'No' END AS NVARCHAR(10)
)
)
I am creating a trigger that checks if another column already has the same value. This however returns a print even if there is no other row with the same value. I believe the mistake is in the IF clause, but I can't figure it out. For the database the following SQL is used.
CREATE TABLE Gebruiker
(
gebruikersnaam VARCHAR(25) NOT NULL,
voornaam VARCHAR(25) NOT NULL,
achternaam VARCHAR(25) NOT NULL,
adresregel_1 VARCHAR(255) NULL,
adresregel_2 VARCHAR(255) NULL,
postcode CHAR(7) NULL,
plaatsnaam VARCHAR(255) NULL,
land VARCHAR(255) NULL,
geboortedag CHAR(10) NOT NULL,
mailbox VARCHAR(255) NOT NULL,
wachtwoord VARCHAR(255) NOT NULL,
verkoper BIT NOT NULL,
CONSTRAINT pk_gebruiker
PRIMARY KEY (gebruikersnaam),
)
CREATE TABLE Verkoper
(
gebruikersnaam VARCHAR(25) NOT NULL,
banknaam VARCHAR(255) NULL,
rekeningnummer VARCHAR(32) NULL,
controleoptienaam CHAR(10) NOT NULL,
creditcardnummer INTEGER NULL,
CONSTRAINT pk_Verkoper
PRIMARY KEY (gebruikersnaam),
CONSTRAINT fk_Verkoper_Gebruikersnaam
FOREIGN KEY (gebruikersnaam) REFERENCES Gebruiker(gebruikersnaam),
CONSTRAINT ck_rekening
CHECK (rekeningnummer is NOT NULL OR creditcardnummer is NOT NULL),
CONSTRAINT ck_controleoptie
CHECK (controleoptienaam IN('Post', 'Creditcard'))
)
CREATE TABLE Voorwerp
(
voorwerpnummer NUMERIC(10) NOT NULL,
titel VARCHAR(255) NOT NULL,
beschrijving VARCHAR(255) NOT NULL,
startprijs NUMERIC(5,2) NOT NULL,
betalingswijze VARCHAR(255) NOT NULL,
betalingsinstructie VARCHAR(255) NOT NULL,
plaatsnaam VARCHAR(255) NOT NULL,
land VARCHAR(255) NOT NULL,
looptijd INTEGER NOT NULL,
looptijdbegindag CHAR(10) NOT NULL,
looptijdbegintijdstip CHAR(8) NOT NULL,
verzendkosten NUMERIC(5,2),
verzendinstructie VARCHAR(255) NOT NULL,
verkoper VARCHAR(25) NOT NULL,
koper VARCHAR(25) NULL,
looptijdeindedag CHAR(10) NOT NULL,
looptijdeindetijdstip CHAR(8) NOT NULL,
veilingGesloten BIT NOT NULL,
verkoopprijs NUMERIC(5,2) NOT NULL,
CONSTRAINT pk_voorwerp
PRIMARY KEY (voorwerpnummer),
CONSTRAINT fk_voorwerp_verkoper
FOREIGN KEY (verkoper) REFERENCES verkoper(gebruikersnaam),
CONSTRAINT fk_voorwerp_gebruiker
FOREIGN KEY (koper) REFERENCES gebruiker(gebruikersnaam)
)
CREATE TABLE Bod
(
voorwerpnummer NUMERIC(10) NOT NULL,
euro NUMERIC(5,2) NOT NULL,
gebruikersnaam CHAR(10) NOT NULL,
datum CHAR(10) NOT NULL,
tijdaanduiding CHAR(8) NOT NULL,
CONSTRAINT pk_Bod
PRIMARY KEY (voorwerpnummer, euro),
CONSTRAINT ak_Bod_Gebruiker_BodDag_Tijdstip
UNIQUE (gebruikersnaam, datum, tijdaanduiding),
CONSTRAINT ak_Bod_Voorwerp_BodDag_Tijdstip
UNIQUE (voorwerpnummer, datum, tijdaanduiding),
CONSTRAINT fk_Bod_Voorwerp
FOREIGN KEY (voorwerpnummer) REFERENCES Voorwerp(voorwerpnummer)
)
INSERT INTO Gebruiker
VALUES ('Lars', 'Lars', 'Last_name', NULL, NULL, NULL, NULL, NULL, '04/04/2019', 'lars#mymailbox.cloud', 'MyPassword', 1)
INSERT INTO Verkoper
VALUES ('Lars', 'ING', 'NL42INGB0685', 'Creditcard', 654654665);
INSERT INTO Voorwerp (voorwerpnummer, titel, beschrijving, startprijs, betalingswijze, betalingsinstructie, plaatsnaam, land, looptijd, looptijdbegindag, looptijdbegintijdstip, verzendkosten, verzendinstructie, verkoper, looptijdeindedag, looptijdeindetijdstip, veilinggesloten)
VALUES (3434343434, 'test', 'test', 10.00, 'bank/giro', 'betaald voor levering', 'Arnhem', 'Nederland', 7, '20/04/2019', '13:30:15', 5.00, 'pakket post', 'Lars', '27/04/2019', '12:30:15', 0);
The trigger in question:
CREATE TRIGGER hoger_bod
ON Bod
FOR INSERT, UPDATE
AS
BEGIN
IF EXISTS (SELECT 1
FROM inserted AS i
WHERE i.voorwerpnummer IN (SELECT voorwerpnummer FROM Bod))
BEGIN
PRINT 'This voorwerpnummer already has a row.';
END;
END;
This trigger should return 'This voorwerpnummer already has a row.' when the Bod column has a row with the same voorwerpnummer value.
To test this I've used the following INSERT statement:
INSERT INTO Bod VALUES (3434343434, 5.01, 'Lars', '12/12/2011', '11:11:16')
This returns 'This voorwerpnummer already has a row.', even though there are no rows.
For a second insert:
INSERT INTO Bod VALUES (3434343434, 10.00, 'Lars', '12/12/2011', '11:16:16')
If you'd like to test this; here is a dbfiddle: https://dbfiddle.uk/?fiddle=1777fa6548beef3ac5e701b7bc2c489c
As per #GuidoG, try:
CREATE TRIGGER hoger_bod ON Bod
FOR INSERT,UPDATE
AS
BEGIN
IF (SELECT COUNT(*)
FROM inserted AS i
WHERE i.voorwerpnummer IN (SELECT voorwerpnummer FROM Bod)) >1
BEGIN
PRINT 'This voorwerpnummer already has a row.';
END;
END;
I have this uni assignment where I am given the script for the database as well as the one for the bulk insert and a dataset of about 1.300.000 records. With the database set up, i ran the bulk insert script and I am getting a bulk load data conversion error.
I asked all my friends if they had a similar experience but none of them had the same issue. I tried to look into that, it would seem that what causes this error to happen is the Date field in the MainTable, so i tried to find how to set the default date to DD/MM/YYYY and to use the / instead of -, all I found was some SELECT that formatted the getdate() function and the SET DATEFORMAT dmy command but that didn't fix my errors. I deleted the database and repeated the process at least 3 times now and I'm getting the same error every time.
CREATE TABLE MainTable
(
bookCode int NULL,
bookDt date NULL,
payCode int NULL,
payMethod char(2) NULL,
custCode int NULL,
custName varchar(30) NULL,
custSurname varchar (30) NULL,
custPhone varchar (20) NULL,
staffNo int NULL,
staffName varchar (30) NULL,
staffSurname varchar (30) NULL,
totalCost numeric(19, 2) NULL,
campCode char(3) NULL,
campName varchar (50) NULL,
numOfEmp int NULL,
empNo int NULL,
catCode char (1) NULL,
areaM2 int NULL,
unitCost numeric(4,2) NULL,
startDt date NULL,
endDt date NULL,
noPers int NULL,
costPerRental numeric(19, 2) NULL
);
SET DATEFORMAT dmy
BULK INSERT mainTable
FROM 'C:\DATA\GeneratedData.txt'
WITH (FIRSTROW = 2,FIELDTERMINATOR= ',', ROWTERMINATOR = '\n');
And a couple of records from the dataset:
2615981,14/08/2018,1,CC,990,Christie,BUCKNER,(+30)000-556-7301,5020,Zaria,RACE,45,ROS,Rosibos,200,151,C,30,15,15/08/2018,17/08/2018,1,45
2616347,17/08/2018,3,CA,403,Ashli,MAXWELL,(+30)000-114-8689,5010,Yovonnda,CAZARES,45,ROS,Rosibos,200,151,C,30,15,18/08/2018,20/08/2018,1,45
The error I am getting is this:
Msg 4864, Level 16, State 1, Line 3
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 2, column 2 (bookDt).
I am getting the same error what appears to be every single row in the text file.
Instead of "Set DateFormat dmy", try the following:
Set Language N'british'
Like I said in my comment, it's often easier to insert the data into a string type column in a staging table, and then convert the values afterwards. I've only done this with the Date columns here, but you can do it to the whole lot if you wish:
USE Sandbox;
GO
CREATE SCHEMA stg;
GO
CREATE TABLE stg.MainTable (bookCode int NULL,
bookDt varchar(10) NULL,
payCode int NULL,
payMethod char(2) NULL,
custCode int NULL,
custName varchar(30) NULL,
custSurname varchar(30) NULL,
custPhone varchar(20) NULL,
staffNo int NULL,
staffName varchar(30) NULL,
staffSurname varchar(30) NULL,
totalCost numeric(19, 2) NULL,
campCode char(3) NULL,
campName varchar(50) NULL,
numOfEmp int NULL,
empNo int NULL,
catCode char(1) NULL,
areaM2 int NULL,
unitCost numeric(4, 2) NULL,
startDt varchar(10) NULL,
endDt varchar(10) NULL,
noPers int NULL,
costPerRental numeric(19, 2) NULL);
GO
BULK INSERT stg.MainTable
FROM 'C:\DATA\GeneratedData.txt'
WITH (FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n');
GO
CREATE TABLE dbo.MainTable (bookCode int NULL,
bookDt date NULL,
payCode int NULL,
payMethod char(2) NULL,
custCode int NULL,
custName varchar(30) NULL,
custSurname varchar(30) NULL,
custPhone varchar(20) NULL,
staffNo int NULL,
staffName varchar(30) NULL,
staffSurname varchar(30) NULL,
totalCost numeric(19, 2) NULL,
campCode char(3) NULL,
campName varchar(50) NULL,
numOfEmp int NULL,
empNo int NULL,
catCode char(1) NULL,
areaM2 int NULL,
unitCost numeric(4, 2) NULL,
startDt date NULL,
endDt date NULL,
noPers int NULL,
costPerRental numeric(19, 2) NULL);
GO
INSERT INTO dbo.MainTable
SELECT bookCode,
CONVERT(date, bookDt, 103),
payCode,
payMethod,
custCode,
custName,
custSurname,
custPhone,
staffNo,
staffName,
staffSurname,
totalCost,
campCode,
campName,
numOfEmp,
empNo,
catCode,
areaM2,
unitCost,
CONVERT(date, startDt, 103),
CONVERT(date, endDt, 103),
noPers,
costPerRental
FROM stg.MainTable;
TRUNCATE stg.MainTable;
I have two databases: identity2 and myDb.
Can someone help me by telling me how I can move the rows in a table with an identity column (AspNetUsers) from one database to another.
CREATE TABLE [dbo].[AspNetUsers] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (MAX) NULL,
[LastName] NVARCHAR (MAX) NULL,
[Email] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[LockoutEndDateUtc] DATETIME NULL,
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[UserName] NVARCHAR (256) NOT NULL,
[SubjectId] INT DEFAULT ((0)) NOT NULL,
[SubjectIds] VARCHAR (50) NULL,
[OrganizationId] INT DEFAULT ((0)) NOT NULL,
[OrganizationIds] VARCHAR (50) NULL,
[RoleId] INT DEFAULT ((0)) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([UserName] ASC);
What I want to do is to preserve the Id numbers but I don't know how to do this.
Create your table like you posted in the question and then do an insert with identity insert
SET IDENTITY_INSERT AspNetUsers ON
INSERT INTO AspNetUsers (
[Id],
[FirstName],
[LastName],
[Email],
[EmailConfirmed],
[PasswordHash],
[SecurityStamp],
[PhoneNumber],
[PhoneNumberConfirmed],
[TwoFactorEnabled],
[LockoutEndDateUtc],
[LockoutEnabled],
[AccessFailedCount],
[UserName],
[SubjectId],
[SubjectIds],
[OrganizationId],
[OrganizationIds],
[RoleId]
)
SELECT * FROM myDB.dbo.AspNetUsers
SET IDENTITY_INSERT AspNetUsers OFF
select *
into [targetdatabase].[dbo].[targettable]
from [sourcedatabase].[dbo].[sourcetable]
maybe I can get some feedback from some folks on this. I created two tables and inserted data into one table and i put a constraint (Foreign key) on the table std_individual_address.
I get the following error message when I try to execute the insert now:
Msg 515, Level 16, State 2, Line 43 Cannot insert the value NULL into
column 'individual_GUID', table 'ABLE.dbo.std_individual_address';
column does not allow nulls. INSERT fails. The statement has been
terminated.
Here is all my code:
--Create the std_individual table
CREATE TABLE std_individual(
individual_GUID INT NOT NULL IDENTITY,
individual_First_Name VARCHAR(50) NULL,
individual_Last_Name VARCHAR(50) NULL,
individual_email VARCHAR(40) NULL,
PRIMARY KEY (individual_GUID));
--Create the std_individual_address table
CREATE TABLE std_individual_address
(
individual_address_GUID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
individual_address_line1 VARCHAR(100) NULL,
individual_address_line2 VARCHAR(100) NULL,
individual_address_line3 VARCHAR(100) NULL,
individual_address_city VARCHAR(50) NULL,
individual_address_state VARCHAR(30) NULL,
individual_address_zipcode VARCHAR(30) NULL,
individual_GUID INT NOT NULL,
CONSTRAINT fk_std_individual_address_std_individual FOREIGN KEY (individual_GUID) REFERENCES std_individual (individual_GUID)
)
--Insert Individual Data
INSERT INTO std_individual
(individual_First_Name,individual_Last_Name,individual_email)
VALUES
('Terry','Smith','tsmith#example.net'),
('Ronald','Smegan','ronald#example.net'),
('Arnold','Aggassi','aaggassi#example.edu'),
('Jerry','Brukheimer','bbrukheimer#example.edu');
--Mind the Constraint
INSERT INTO std_individual_address(individual_GUID) SELECT individual_GUID from std_individual
--Attempt to insert rest of the data
INSERT INTO std_individual_address
(individual_address_line1,individual_address_line2,individual_address_city,individual_address_state,
individual_address_zipcode )
VALUES
('8200 Greensboro Drive','Ste 1500','Mclean','Virgina','22102'),
('1121 14th Street, NW','Ste 1000','Washington' ,'District of Columbia','20005'),
('1700 Connecticut Ave,NW','Ste 300','Washington' ,'District of Columbia','20009'),
('205 Pennsylvania Ave,SE','','Washington','District of Columbia','20003');
Then I get the error message above. Any ideas on how to combat that issue?