Unable to add column using ALTER - sql

I'm creating a table using the following code
CREATE TABLE [dbo].[t_emp](
[empid] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[salary] [numeric](10, 2) NOT NULL,
[dept] [nvarchar](50) NOT NULL)
And also i'm trying to add column using the following code,
alter table t_emp add column ename varchar(50) not null
But i'm getting the following error,
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'column'.
Please guide me the correct way to achieve my objective.

Use Command without Column
Aَlter Table t_emp Add ename varchar(50) not null

Related

Alter column properties in SQL [duplicate]

This question already has answers here:
Default getdate for Insert date
(9 answers)
Closed 8 years ago.
I am trying to make a change to the data type for a column in an existing table. This column currently is empty but the table has dependencies which makes it impractical to drop and recreate the table.
The table currently looks like:
CREATE TABLE [dbo].[van_Payment](
[PaymentUID] [int] IDENTITY(1,1) NOT NULL,
[SponsorshipUID] [int] NOT NULL,
[PaymentMethodUID] [int] NOT NULL,
[Amount] [int] NOT NULL,
[Created] [int] NOT NULL,
GO
I need to change the following:
ALTER TABLE [dbo].[van_Payment]
ALTER COLUMN [Created] [smalldatetime] NOT NULL DEFAULT GETDATE(),
GO
I am getting the following error:
Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword
'DEFAULT'.
Any help with the correct syntax would be appreciated.
I don't think it possible to add default constraint using alter column syntax. Try this.
ALTER TABLE [dbo].[van_Payment]
ALTER COLUMN [Created] [smalldatetime] NOT NULL
GO
ALTER TABLE dbo.[van_Payment] ADD CONSTRAINT DF_Created DEFAULT getdate() FOR [Created];

SQL create statement incorrect syntax near auto increment

I created the following table, but I got the error below;
Incorrect syntax near 'AUTO_INCREMENT'.
SQL:
CREATE TABLE [dbo].[MY_TABLE] (
[ID] INT NOT NULL AUTO_INCREMENT,
[NAME] NVARCHAR (100) NULL,
[SCHOOL] NVARCHAR (100) NULL,
PRIMARY KEY (ID)
);
I think I have done everything right. Can someone help me out?
It is IDENTITY not AUTO_INCREMENT in SQL Server.
Try this instead:
CREATE TABLE [dbo].[MY_TABLE] (
[ID] INT NOT NULL IDENTITY(1, 1),
[NAME] NVARCHAR (100) NULL,
[SCHOOL] NVARCHAR (100) NULL,
PRIMARY KEY (ID)
);
Its not AUTO_INCREMENT. Here the Demo from sqlfiddle
Use IDENTITY for MSSQL as shown below. *AUTO_INCREMENT is for MySQL and MariaDB:
CREATE TABLE [dbo].[MY_TABLE] (
[ID] INT NOT NULL IDENTITY, -- Here
...
);
In addition, you can have a custom IDENTITY with "()" as shown below. The 1st argument is for start value and the 2nd argument is for increment value so in the example below, if first inserting a row, ID is 20 and if second inserting a row, ID is 23, then ID is 26, 29, 32...:
-- Increment value
CREATE TABLE [dbo].[MY_TABLE] (-- ↓
[ID] INT NOT NULL IDENTITY(20, 3),
... -- ↑
); -- Start value
And, IDENTITY is equivalent to IDENTITY(1, 1).

ERROR Column CHECK constraint for column references another column

I use MS SQL 2008 R2, I need create a Table with a CHECK on a specific column but I receive this error. Could you please point me out in the right direction? Thanks
HeatingSystem tinyint NOT NULL
CONSTRAINT CK_ReProperties_HeatingSystem CHECK(Size between 0 and 3),
ERROR
Msg 8141, Level 16, State 0, Line 1
Column CHECK constraint for column 'HeatingSystem' references another column, table 'ReProperties'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Constraints that are defined inline at column level can only reference the column they are defined next to.
Either move the constraint definition next to the correct column or move the constraint definition to the end of the table definition.
Fails
CREATE TABLE HeatingSystem
(
Size INT,
HeatingSystem TINYINT CHECK(Size between 0 and 3)
)
Succeeds
CREATE TABLE HeatingSystem
(
Size INT CHECK(Size between 0 and 3),
HeatingSystem TINYINT
)
Also Succeeds
CREATE TABLE HeatingSystem
(
Size INT ,
HeatingSystem TINYINT,
CHECK(Size between 0 and 3 AND HeatingSystem BETWEEN 1 AND 10)
)
The final way also allows you to declare a row level constraint referencing multiple columns.
With your comment, I don't understand where "Size" is coming from...
Can't you just make
CONSTRAINT CK_ReProperties_HeatingSystem CHECK(HeatingSystem between 0 and 3)
Here how I have solved.
HeatingSystem tinyint NOT NULL
CONSTRAINT CK_ReProperties_HeatingSystem CHECK(HeatingSystem between 0 and 3),
I tried your query and it is giving me error as Invalid column name 'Size'. You should write the columnname - HeatingSystem in place of size. Use the following:-
HeatingSystem tinyint NOT NULL
CONSTRAINT CK_ReProperties_HeatingSystem CHECK(HeatingSystem between 0 and 3),
You may be just missing a comma separator before the word CONSTRAINT !!
e.g.) if "," after ([WorkLocationId]) in below snippet is missing then, it will throw ERROR Column CHECK constraint for column references another column error.
This will throw error -
CREATE TABLE [MYSYSTEM].[User](
[UserId] int Primary key NOT NULL,
[UserName] [nvarchar](50) NULL,
[UserStatus] [nvarchar](1) NULL,
[CreatedDate] [Datetime] NOT NULL,
[WorkLocationId] int NOT NULL Foreign Key References [HRSYSTEM].[WorkLocations]([WorkLocationId])
CONSTRAINT [_UserStatusValues] CHECK ([UserStatus] IN ('A','I') )
)
This will work -
CREATE TABLE [MYSYSTEM].[User](
[UserId] int Primary key NOT NULL,
[UserName] [nvarchar](50) NULL,
[UserStatus] [nvarchar](1) NULL,
[CreatedDate] [Datetime] NOT NULL,
[WorkLocationId] int NOT NULL Foreign Key References [HRSYSTEM].[WorkLocations]([WorkLocationId]),
CONSTRAINT [_UserStatusValues] CHECK ([UserStatus] IN ('A','I') )
)
Just use a table level constraint, i.e move the constraint to the end of the table definition.

SQL Server IDENTITY column

How can I modify this command in order to have an identity column which has five digits integer like 00000 and start from 00001 ?
CREATE TABLE [dbo].[Company]
(
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](200) NOT NULL
)
An integer does not have any leading 0 by itself. It is a formatting issue to deal with when converting the integer to a string for displaying.
If you really, really need to be able to present such a string right out of SQL, you can do it with a computed column:
CREATE TABLE [dbo].[Company](
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[FormattedCompanyId] AS RIGHT('0000'+ CONVERT(VARCHAR,Num),5),
[Name] nvarchar NOT NULL,
I would never use that solution myself though, formatting doesn't belong in the data store.
You need to add the leading zeros yourself. As a solution you can add an other colomn named say "formatedID" and update it with an "after insert trigger" with the value from the identity column and formatted with the leading zeros you want to.
Example :
CREATE TABLE [dbo].[Company]
(
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[FormattedID] [VARCHAR(20)],
[Name] [nvarchar](200) NOT NULL
)
CREATE TRIGGER ON [dbo].[Company]
FOR INSERT
AS
BEGIN
UPDATE [dbo].[Company]
FROM inserted
SET FormattedID = RIGHT('0000'+ CONVERT(VARCHAR, [dbo].[Company].CompanyId),5)
WHERE dbo.Company.CompanyId = inserted.CompanyId
END

MSG 2714 There is an object already named

I'm using sql server 2008 management studio. Im trying to create two seemingly simple tables but continue getting this error at execution. I have tried changing the names of these tables to many different variations. Nothing is helping. Here below is what I am typing.
USE POS410;
go
CREATE TABLE [empl]
(
employeeID INT NOT NULL,
lname VARCHAR(15) NOT NULL,
fname VARCHAR(15) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(15) NOT NULL,
state VARCHAR(10) NOT NULL,
areacode INT NOT NULL,
tnumber INT NOT NULL,
EEO1classification VARCHAR(10) NOT NULL,
hiredate DATE NOT NULL,
salary INT NOT NULL,
gender VARCHAR(1) NOT NULL,
age INT NOT NULL,
clocknumb INT NOT NULL,
PRIMARY KEY(employeeID),
UNIQUE(employeeID),
UNIQUE(clocknumb),
FOREIGN KEY(clocknumb) REFERENCES [jb_ttl](Empnum),
);
go
CREATE TABLE [jb_ttl]
(
EEO1 VARCHAR(10) NOT NULL,
JobTitle VARCHAR(15) NOT NULL,
JobDscrpt TEXT NOT NULL,
ExemptNonExemptStatus VARCHAR NOT NULL,
Empnum INT NOT NULL,
PRIMARY KEY (Empnum),
);
go
Here is the error report:
Msg 2714, Level 16, State 6, Line 2 There is already an object named 'empl' in the database. Msg 2714, Level 16, State 6, Line 2 There is already an object named 'jb_ttl' in the database.
I would say that you've tried to run this script more than once. It would have failed the first time because you're trying to create the first table with a foreign key to the second, which didn't exist yet. I use the word "didn't" because if my guess is correct, it does now, and that's why you're getting the object already exists error.
As a side note, SQL has supported wrapping DDL (creating/modifying objects) at least going back to 2005. I normally wrap table changes in transactions, and don't commit the transaction until everything goes through with no error messages.
Give this a run to confirm if jb_ttl already exists:
select * from master.dbo.sysobjects where [name] = 'jb_ttl'
That will show you if anb object named jb_ttl already exists. Could it already exist as a procedure or trigger perhaps?