I have a small problem with my code. I added a default constraint but for some reason it doesn't want to work. My code:
CREATE TABLE oc.students
(
stud_id INT PRIMARY KEY IDENTITY (1,1),
first_name VARCHAR(50) NOT NULL,
mid_name VARCHAR(50),
last_name VARCHAR(50) NOT NULL,
DOB DATE,
email VARCHAR (255) NOT NULL,
country VARCHAR(50) NOT NULL,
phone VARCHAR(20),
reg_date DATE NOT NULL
);
ALTER TABLE oc.students
ADD DEFAULT GETDATE() FOR [reg_date];
INSERT INTO oc.students (first_name, mid_name, last_name, DOB, email, country, phone, reg_date)
VALUES ('John', '', 'Smith', '1986-12-24', 'js#gmail.com', 'Malta', 123456789, '')
SELECT *
FROM oc.students
Result:
What could be the problem?
'' and NULL are not the same (well, in any database other than Oracle). The first is a string that happens to have no characters. The second is a SQL constant value that has the semantics of "unknown value" and is often used for missing values.
You are inserting '' which is interpreted as 0, which gets converted to the base date. Actually, the technical term for this is epoch, which is the date a uses to start counting date/time values.
If you want the default, you can use:
VALUES (
'John',
'',
'Smith',
'1986-12-24',
'js#gmail.com',
'Malta',
123456789,
DEFAULT
)
Or, more commonly, the column is just left out:
INSERT INTO oc.students (
first_name,
mid_name,
last_name,
DOB,
email,
country,
phone)
VALUES (
'John',
'',
'Smith',
'1986-12-24',
'js#gmail.com',
'Malta',
123456789
)
Related
I am just a student and I am trying to get a table working but have tried everything I could only to end up with an error.
ORA-00933: SQL command not properly ended
Could anyone please help me understand what I'm doing wrong?
CREATE TABLE student
(
idnumber VARCHAR2(8),
firstname VARCHAR2(20),
lastname VARCHAR2(20),
dateofbirth DATE,
address VARCHAR2(20),
email VARCHAR2(20),
programme VARCHAR2(5),
points number(3),
PRIMARY KEY (idnumber)
);
INSERT INTO student
VALUES ('D1234567', 'Student ONE', 'TWO THREE', DATE '2000-05-10',
'Thetown, the address', 'd1234567#mydit.ie', 'DT228', '380'),
('D2345678', 'Student TWO', 'FOUR FIVE', DATE '2000-04-10',
'Thetown, the address', 'd2345678#mydit.ie', 'DT228', '280');
SELECT
firstname, lastname
FROM
student
WHERE
points > 300;
That is not valid insert syntax. You can only insert one row at a time that way, separating by comma will not work. To do multi-row inserts, use the syntax:
INSERT ALL
INTO tbl (col1, col2) VALUES ('value', 'another value')
INTO tbl (col1, col2) VALUES ('value', 'another value')
INTO tbl (col1, col2) VALUES ('value', 'another value')
SELECT 1 FROM DUAL;
The select 1 from dual is required for the subquery needing a select statement. It's no different than doing multiple insert statements, so you might as well just break this into multiple statements unless you are doing thousands of inserts at once.
Run each of the statements one by one:
Create your table
CREATE TABLE student
(
idnumber VARCHAR2(8),
firstname VARCHAR2(20),
lastname VARCHAR2(20),
dateofbirth DATE,
address VARCHAR2(20),
email VARCHAR2(20),
programme VARCHAR2(5),
points number(3),
PRIMARY KEY (idnumber)
);
Insert the 1st row
INSERT INTO student VALUES
(
'D1234567',
'Student ONE',
'TWO THREE',
DATE '2000-05-10',
'Thetown,thedress',
'd1234567#mydit.ie',
'DT228',
'380'
);
Insert the 2nd row
INSERT INTO student VALUES
(
'D2345678',
'Student TWO',
'FOUR FIVE',
DATE '2000-04-10',
'Thetown,the adress',
'd2345678#mydit.ie',
'DT228',
'280'
);
Run the select
SELECT firstname, lastname
FROM student
WHERE points > 300;
Examples:
https://dbfiddle.uk/?rdbms=oracle_18&fiddle=d01055a94dce5ed7919a3d26c8a9f73c
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d01055a94dce5ed7919a3d26c8a9f73c
semicolon (;) is the problem, remove semicolon from last statement and you can get rid of this error, your code's last statement will become
SELECT firstname, lastname
FROM student
WHERE points > 300
Hope this will work
I want to insert following info in the table but it is giving me following error from the following code:
Msg 109, Level 15, State 1, Line 1
There are more 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 registration
(
id int identity primary key,
first_name varchar(100),
last_name varchar(100),
username varchar(100),
[password] varchar(100),
email varchar(100),
[address] varchar(100),
gender varchar(10),
dob date,
reg_date date,
country varchar(50),
city varchar(50),
[status] bit
)
select * from registration
insert into registration (first_name,last_name,username,password,email,[address],gender,dob,reg_date,country,city,status)
values ('Ali','Khan','alik','123','alikhan#gmail.com','Male','19930318','20170318','Pakistan','Karachi')
The error is pretty clear, you are missing some of the columns in the values. Try this:
insert into registration (first_name,last_name,username,password,email,[address],gender,dob,reg_date,country,city,status)
values ('Ali','Khan','alik','123','alikhan#gmail.com','100 Sample Street Address', 'Male','19930318','20170318','Pakistan','Karachi', cast(1 as bit))
Look at your query like this:
Column Value you want to insert
----------- ------------------------
first_name 'Ali'
last_name 'Khan'
username 'alik'
password '123'
email 'alikhan#gmail.com'
[address] 'Male'
gender '19930318'
dob '20170318'
reg_date 'Pakistan'
country 'Karachi'
city
status
You are missing a few values. The error clearly says that.
The values specified in the values clause and the insert statement are equal in numbers. That's where my problem is
I would like to take some data from a table from DB1 and insert some of that data to a table in DB2.
How would one proceed to do this?
This is what I've got so far:
CREATE VIEW old_study AS
SELECT *
FROM dblink('dbname=mydb', 'select name,begins,ends from study')
AS t1(name varchar(50), register_start date, register_end date);
/*old_study now contains the data I wanna transfer*/
INSERT INTO studies VALUES (nextval('studiesSequence'),name, '',3, 0, register_start, register_end)
SELECT name, register_start, register_end from old_study;
This is how my table in DB2 looks:
CREATE TABLE studies(
id int8 PRIMARY KEY NOT NULL,
name_string VARCHAR(255) NOT NULL,
description VARCHAR(255),
field int8 REFERENCES options_table(id) NOT NULL,
is_active INTEGER NOT NULL,
register_start DATE NOT NULL,
register_end DATE NOT NULL
);
You should include the column names in both the insert and select:
insert into vip_employees(name, age, occupation)
select name, age, occupation
from employees;
However, your data structure is suspect. Either you should use a flag in employees to identify the "VIP employees". Or you should have a primary key in employees and use this primary key in vip_employees to refer to employees. Copying over the data fields is rarely the right thing to do, especially for columns such as age which are going to change over time. Speaking of that, you normally derive age from the date of birth, rather than storing it directly in a table.
INSERT INTO studies
(
id
,name_string
,description
,field
,is_active
,register_start
,register_end
)
SELECT nextval('studiesSequence')
,NAME
,''
,3
,0
,register_start
,register_end
FROM dblink('dbname=mydb', 'select name,begins,ends from study')
AS t1(NAME VARCHAR(50), register_start DATE, register_end DATE);
You can directly insert values that retured by dblink()(that means no need to create a view)
Loop and cursor are weapons of last resort. Try to avoid them. You probably want INSERT INTO ... SELECT:
INSERT INTO x(x, y, z)
SELECT x, y, z
FROM t;
SqlFiddleDemo
EDIT:
INSERT INTO vip_employees(name, age, occupation) -- your column list may vary
SELECT name, age, occupation
FROM employees;
Your syntax is wrong. You cannot have both, a values clause for constant values and a select clause for a query in your INSERT statement.
You'd have to select constant values in your query:
insert into studies
(
id,
name_string,
description,
field,
is_active,
register_start,
register_end
)
select
studiesSequence.nextval,
name,
'Test',
null,
0,
register_start,
register_end
from old_study;
I'm taking a SQL class, and on one of the assignments I am asked to create a table with employees, one with projects, as follows:
create table [EMPLOYEE]
(
EmployeeID int identity(1, 1) primary key not null,
FirstName varchar(15) not null,
LastName varchar(15) not null,
Gender char(1) not null,
DOB date not null,
SSN char(9) not null
)
create table [PROJECT]
(
ProjectID int identity(1, 1) primary key not null,
Manager int not null,
PDescription varchar(50) not null,
PStatus varchar(20) not null,
StartDate date not null,
EndDate date not null
)
Where the Manager is the ID of an EMPLOYEE entity. Basically projects are assigned to employees. So, I add some employees and projects
insert into EMPLOYEE (FirstName, LastName, Gender, DOB, SSN)
values ('Chuck', 'Carter', 'M', '07/14/1990', '444556666')
This is the one employee I'm interested in, and in the inserting I'm doing this is the second one, so its EmployeeID would be 2. As for the projects:
insert into PROJECT (Manager, PDescription, PStatus, StartDate, EndDate)
values (2, 'Submit source code for 3D racing game', 'In progress', '01/05/2015', '03/05/2015')
insert into PROJECT (Manager, PDescription, PStatus, StartDate, EndDate)
values (2, 'Test videogame for bugs', 'Not started', '03/05/2015', '05/05/2015')
These two are the ones assigned to the employee above, notice Manager for both is 2, and the EmployeeID of Chuck is supposed to be 2. So, I'm supposed to display the employee name as a full name, combining the first and last name, of those who have been assigned two or more projects (in this case, Chuck).
I wrote this code:
select
FirstName + LastName as FullName
from
EMPLOYEE
where
EmployeeID = PROJECT.Manager and count(PROJECT.Manager) >= 2
But instantly I get this error:
The multi-part identifier "PROJECT.Manager" could not be bound.
Am I supposed to make an inner join to recognize the PROJECT table? But I'm only supposed to display the name of the employee. How can I manage to use the PROJECT.manager column values without displaying them?
Thank you very much in advance.
You have to Join Project table, Add Group by with having clause to filter the Manager
select FirstName +' '+ LastName as FullName
from EMPLOYEE
INNER JOIN PROJECT
on EmployeeID = PROJECT.Manager
group by FirstName +' '+ LastName
Having count(PROJECT.Manager) >= 2
I want to automatically generate unique id with per-defined code attach to it.
ex:
UID12345678
CUSID5000
I tried uniqueidentifier data type but it generate a id which is not suitable for a user id.
Any one have suggestions?
The only viable solution in my opinion is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblUsers without specifying values for ID or UserID:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.
Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:
CREATE TABLE dbo.tblUsers
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
[Name] VARCHAR(50) NOT NULL,
)
marc_s's Answer Snap
Reference:https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017
-- Creating a table using NEWID for uniqueidentifier data type.
CREATE TABLE cust
(
CustomerID uniqueidentifier NOT NULL
DEFAULT newid(),
Company varchar(30) NOT NULL,
ContactName varchar(60) NOT NULL,
Address varchar(30) NOT NULL,
City varchar(30) NOT NULL,
StateProvince varchar(10) NULL,
PostalCode varchar(10) NOT NULL,
CountryRegion varchar(20) NOT NULL,
Telephone varchar(15) NOT NULL,
Fax varchar(15) NULL
);
GO
-- Inserting 5 rows into cust table.
INSERT cust
(CustomerID, Company, ContactName, Address, City, StateProvince,
PostalCode, CountryRegion, Telephone, Fax)
VALUES
(NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,
'90110', 'Finland', '981-443655', '981-443655')
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',
'08737-363', 'Brasil', '(14) 555-8122', '')
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,
'1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,
'8010', 'Austria', '7675-3425', '7675-3426')
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,
'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');
GO
If you want to add the id manually you can use,
PadLeft() or String.Format() method.
string id;
char x='0';
id=id.PadLeft(6, x);
//Six character string id with left 0s e.g 000012
int id;
id=String.Format("{0:000000}",id);
//Integer length of 6 with the id. e.g 000012
Then you can append this with UID.
The 'newid()' method unique id generate for per record.
AddColumn("dbo.Foo", "Key", c => c.String(nullable: false, maxLength: 250, defaultValueSql: "newid()"));
Table Creating
create table emp(eno int identity(100001,1),ename varchar(50))
Values inserting
insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')
Select Table
select * from emp
Output
eno ename
100001 narendra
100002 rama
100003 ajay
100004 anil
100005 raju