Insert into a new Table in SQL gives error - sql

Why am I getting an error?
--Q1
CREATE table Aorders (
Id INT IDENTITY NOT NULL,
CreatedDate Date NOT NULL,
BillingCountry varchar Not Null,
MerchId int Not null,
OrderStatus varchar Not null,
);
--Q2
select * from Aorders
--Q3 edited as suggested here but still get an error
INSERT INTO Aorders (CreatedDate, BillingCountry, MerchId, OrderStatus)
VALUES ('2001-01-01', 'Israel', 5 ,'Approved');

You must define the length of the varchar columns like:
CREATE table Aorders (
Id INT IDENTITY NOT NULL,
CreatedDate Date NOT NULL,
BillingCountry varchar(100) Not Null,
MerchId int Not null,
OrderStatus varchar(100) Not null,
);
From char and varchar (Transact-SQL):
When n isn't specified in a data definition or variable declaration
statement, the default length is 1

When doing an insert, the best practice is to list all the columns explicitly and to use standard formats for dates:
INSERT INTO Aorders (CreatedDate, BillingCountry, MerchId, OrderStatus)
VALUES ('2001-01-01', 'Israel', 5 ,'Approved');
Your specific error is because you have four values in the VALUES() list but there are five columns in the table.

You have not done your query properly. I think you want the ID to auto increment ,but you haven't declare that. Make changes as below:
CREATE table Aorders ( Id INT IDENTITY NOT NULL
,CreatedDate Date NOT NULL
,BillingCountry varchar Not Null
,MerchId int Not null
,OrderStatus varchar Not null);
Now enter the query as you have inserted. And also make sure proper date formats from documentation.

Related

SQLServer how to convert single row values in to multiple rows with each property as separat

I have a user defined type which is passed to my sql stored procedure:
CREATE TYPE [dbo].[LearningDelivery] AS TABLE(
[LearnAimRef] NVARCHAR(10) NOT NULL,
[AimType] INT NOT NULL,
[AimSeqNumber] INT NOT NULL,
);
i have a table with structure as below. I want to match join the type name from the above definition into the ElementName column of the FieldDefinitation table and insert separate insert statements. can anyone help me how to achieve this?
CREATE TABLE [dbo].[LearningAimData]
(
[Id] INT IDENTITY(1, 1) NOT NULL,
[LearnerId] INT NOT NULL,
[FieldId] INT NOT NULL,
[Data] VARCHAR(128) NOT NULL
)
I want to insert each type i.e LearnAimRef , AimType as individual row values in the LearningAimData.
I have a lookup table for [FieldId]
CREATE TABLE [dbo].[FieldDefinition]
(
[Id] INT IDENTITY(1, 1),
[FieldId] INT NOT NULL,
[Name] VARCHAR(50) NOT NULL,
[ElementName] VARCHAR(50) NOT NULL
)

An aggregate may not appear in a computed column expression or check constraint. error while using MAX function

I am receiving
An aggregate may not appear in a computed column expression or check constraint error
while using MAX function for a date column to create a table. Here is the code I'm using to create the table:
Create table Bills
(
BillNo INT NOT NULL,
MeterNo INT NOT NULL,
FirstDate datetime NOT NULL,
FirstDateReading INT NOT NULL,
CurrentDate as MAX(FirstDate),
CurrentDateReadng INT NOT NULL,
LastDate as DATEADD(m,-1,CurrentDate),
LastDateReading INT NOT NULL,
Usageinm3 as (CurrentDateReadng-LastDateReading),
Usageinlitres as (Usageinm3 * 1000),
TotalBill as (UsageinLitres * 3)
Primary Key (BillNo),
Foreign Key (MeterNo) References MeterReading(MeterNo)
);
Since you are defining the table structure, you should put the data type for each column, not the value.
Create table Bills
(
BillNo INT NOT NULL,
MeterNo INT NOT NULL,
FirstDate datetime NOT NULL,
FirstDateReading INT NOT NULL,
CurrentDate as DATE, <--should be the data type
...
If you are creating a table based on other tables, you should use something like
SELECT billno,
meterno,
firstdate,
firstdatereading,
MAX(firstdate)
...
INTO Bills
FROM sourcetable
WHERE conditions
GROUP BY billno,
meterno,
firstdate,
firstdatereading
...

How can I debug a SQL Server trigger that is giving error "Conversion failed when converting date and/or time from character string"?

I have a C# app with a SQL Server backend. In the backend I have two tables:
MyTable
MyTableHistory
I just added a trigger to put an entry in MyTableHistory when you do an update on MyTable. I am getting and error when I add this trigger:
Conversion failed when converting date and/or time from character
string
Here is the trigger:
CREATE TRIGGER [TU_MyTable]
ON dbo.[MyTable]
AFTER UPDATE
AS
SET NOCOUNT ON
INSERT INTO dbo.[MyTableHistory]
SELECT *
FROM deleted
GO
Here is my table schema
CREATE TABLE dbo.[MyTable]
(
[Id] int IDENTITY NOT NULL
CONSTRAINT [PK_MyTable] PRIMARY KEY,
[Timestamp] NOT NULL,
[IsDeleted] bit NOT NULL,
[Name] nvarchar(200) NOT NULL,
[LastUpdated] datetime NOT NULL,
[LastUpdatedBy] nvarchar(50) NOT NULL
)
GO
and here is the history table schema
CREATE TABLE dbo.[MyTableHistory]
(
[Id] int NOT NULL,
[Timestamp] binary(8) NOT NULL,
[IsDeleted] bit NOT NULL,
CONSTRAINT [PK_MyTableHistory] PRIMARY KEY ([Id], [Timestamp]),
[LastUpdated] datetime NOT NULL,
[LastUpdatedBy] nvarchar(50) NOT NULL,
[Name] nvarchar(200) NOT NULL
)
GO
Is there anyway to figure out what field is causing this issue and is there anyway to debug inside the database trigger to help me diagnose?
The error is due to conversion of NVARCHAR to DATETIME. In MyTable, the column Name is placed before the LastUpdated column. In short, the order of columns in both tables is not the same. You should specify the columns in your INSERT statement.
INSERT INTO MyTableHistory(
Id,
[Timestamp],
IsDeleted,
Name,
LastUpdated,
LastUpdatedBy
)
SELECT
Id,
[Timestamp],
IsDeleted,
Name,
LastUpdated,
LastUpdatedBy
FROM deleted
Doing an insert without a column list is dangerous. Include the list and don't use *:
Insert into dbo.[MyTableHistory]([Id], [Timestamp], [IsDeleted], [LastUpdated],
[LastUpdatedBy], [Name])
SELECT id, [Timestamp], IsDeleted, LastUpdated, LastUpdatedBy, Name
from deleted;
Do not depend on the ordering of columns in a table -- it causes bugs that are hard to find.

How to insert data to multiple tables in C#

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT VARCHAR (255),
PRIMARY KEY (ID)
);
I want to insert data into both table at a time, i.e. inserting the ID from table CUSTOMERS into Customer_ID in table ORDERS.
Please help me!
TRY THIS
DECLARE #CustomerID INT
INSERT INTO Customer ...
SELECT #CustomerID = SCOPE_IDENTITY() FROM Customer
You'll get the last inserted customer ID and then insert to order table.

SQL 2008 create table method and KEY

I've got a script that generates a table - only my version of SQL 2008 throws up an error - has the syntax changed? Or how do I fix it manually?
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL ,
SessionID int NOT NULL ,
ScoID varchar (255) NOT NULL ,
StudentID varchar (255) NOT NULL ,
DateRecorded datetime NULL ,
score_raw varchar (12) NULL,
KEY student_course_sess_scohist_idx (StudentID, CourseID, SessionID, ScoID) -- this is the bit it doesn't like! It says incorrect syntax near KEY...
);
Many thanks in advance,
Spud
You can define a named primary key table constraint like this:
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL,
SessionID int NOT NULL,
ScoID varchar (255) NOT NULL,
StudentID varchar (255) NOT NULL,
DateRecorded datetime NULL,
score_raw varchar (12) NULL,
CONSTRAINT student_course_sess_scohist_idx PRIMARY KEY (StudentID, CourseID, SessionID, ScoID)
);
It would work like this, if this is the intended behaviour:
CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL ,
SessionID int NOT NULL ,
ScoID varchar (255) NOT NULL ,
StudentID varchar (255) NOT NULL ,
DateRecorded datetime NULL ,
score_raw varchar (12) NULL,
PRIMARY KEY (StudentID, CourseID, SessionID, ScoID)
);
It you would only like to create a non-unique index on the table, create the index using the CREATE INDEX statement.
CREATE TABLE ScoHistory
(
CourseID varchar(255) NOT NULL
,SessionID int NOT NULL
,ScoID varchar(255) NOT NULL
,StudentID varchar(255) NOT NULL
,DateRecorded datetime NULL
,score_raw varchar(12) NULL,
) ;
ALTER TABLE dbo.ScoHistory ADD
CONSTRAINT PK_ScoHistory PRIMARY KEY (StudentID, CourseID, SessionID, ScoID);