I'm new in using SQL Server and right now I'm trying to change "Id" column from default ID to GUID.
When using this code
ALTER TABLE dbo.Bookings ALTER COLUMN Id UNIQUEIDENTIFIER DEFAULT NEWID();
It gets me an error
Incorrect syntax near 'DEFAULT'
And I don't understand where is the syntax problem.
Can anyone point it out what is causing this error?
You should use the add constraint syntax:
ALTER TABLE dbo.Bookings ADD CONSTRAINT DF_dbo_Bookings_Id DEFAULT(NEWID()) FOR Id;
Also, if your table have the primary key clustered on that Id column, you could use the NEWSEQUENTIALID for creating unique identifiers that will have less impact on your writes:
ALTER TABLE dbo.Bookings ADD CONSTRAINT DF_dbo_Bookings_Id DEFAULT(NEWSEQUENTIALID()) FOR Id;
Example, on dbfiddle
ALTER TABLE dbo.Bookings
ALTER COLUMN id UNIQUEIDENTIFIER ;
ALTER TABLE dbo.Bookings
ALTER id SET DEFAULT NEWID();
Its possible using the alters separately.
Its the best to backup current table to avoid potential data loss.
Related
In SQL Server 2016 Express, I initially made a table with a primary key that used the int datatype. Now, further into the project, I've realized that I need this column to be a string datatype, but when I try this:
alter table ExpAwbs
drop constraint PK_ExpAwbs;
alter table ExpAwbs
alter column idExpAwbs varchar(12);
alter table ExpAwbs
add constraint PK_ExpAwbs primary key (idExpAwbs);
I get this
Msg 4902, Level 16, State 1, Line 1
Cannot find the object "ExpAwbs" because it does not exist or you do not have permissions.
Is it possible to do what I'm trying to do on a temporal table, or do I need to remake the table?
Try this :
Use YourDatabaseName
Go
alter table ExpAwbs
drop constraint PK_ExpAwbs;
alter table ExpAwbs
alter column idExpAwbs varchar(12);
alter table ExpAwbs
add constraint PK_ExpAwbs primary key (idExpAwbs);
If this not working that mean that the user do not have permissions, So you have to change the user or Grant the permission for that user.
As #wei_dba mentioned, it most certainly seems to be a permission issue. To prove that, I recreated your table, added some data to it and tried it - it worked. If you're unable to do so, clearly the issue lies within the area of permissions; you may need to have someone run that query for you.
While reviewing your query, I see another issue with a quick fix. You may want to replace the following:
alter table ExpAwbs
alter column idExpAwbs varchar(12);
with
alter table ExpAwbs
alter column idExpAwbs varchar(12) not null;
Reasoning being that you need to make sure that the PK is non-nullable, something which you haven't put into your query.
I want to add a Column to a table in my Database. As several data already exist in that particular table , MSSQL does not allow me to add a not Null field. So I can use a default keyword to solve this problem and run the below mentioned Query -
Alter table ServiceDetails
Add OCF_Internal_ID varchar(50) not null default 'OCF';
But now I want to make the "OCF_Internal_ID" field Primary key and I need to insert unique values to the every record of that particular filed. Please give me any suggestion.
How can I add Unique values to all the existing records ?
You can use one of these options
Alter table ServiceDetails
Add OCF_Internal_ID integer NOT NULL IDENTITY (1,1);
OR
Alter table ServiceDetails
Add OCF_Internal_ID uniqueidentifier NOT NULL default newid();
Then run this do define a primary key constraint
ALTER TABLE ServiceDetails
ADD CONSTRAINT PK_ServiceDetails_OCF_Internal_ID PRIMARY KEY CLUSTERED (OCF_Internal_ID);
GO
I am adding a new column in an existing table with preloaded data. This column uses a primary key from another table and I want to default this to 5. I have tried the following code:
ALTER TABLE group
ADD group_type INT
GO
ALTER TABLE group
ADD CONSTRAINT FK_group_type DEFAULT 5 FOR group_type
GO
I was expecting on alter of the group table then all the values will be filled with 5 but instead its NULL. What am I doing wrong?
First of all, adding a DEFAULT constraint (in it's own SQL statement) to a column does not effect existing data in that column. It only effects new INSERTS to that table which do not provide a value for that column.
Second, you haven't created a FOREIGN KEY constraint here.
EDIT:
Here would be one way to create the FK correctly
ALTER TABLE group
ADD group_type_id INT
GO
ALTER TABLE group
ADD CONSTRAINT fk_groupType FOREIGN KEY (group_type_id)
REFERENCES group_type (group_type_id)
This worked for me, it set the foreign key constraint, default value, and updated existing table records all in a single ALTER TABLE statement. I'm using a SQL Azure database (via SQL Management Studio), so, YMMV.
ALTER TABLE Group
ADD GroupTypeId int NOT NULL
CONSTRAINT DK_GroupTypeId DEFAULT (5) WITH VALUES
CONSTRAINT FK_GroupTypeId FOREIGN KEY
REFERENCES [dbo].[GroupType] (GroupTypeId)
GO
It took a while to run, but a subsequent select, showed the rows had the correct default value for those columns.
Disclaimer: I edited the above query from my table / key names to yours without re-testing it, so you may want to double check it for any typos or other mismatches; The syntax should be the same though.
You can use:
alter table [group]
add group_type int constraint df_group_type default (5) with values
However, it doesn't seem a good idea to use constant as a default value for a column, which is supposed to be FK column.
It seems, that may be what actually you are trying to do is following:
alter table [group] add column group_type int
GO
update [group] set group_type = (select id from group_type where desc ='typeA')
GO
alter table [group] add constraint FK_group_grouptype foreign key (group_type) references group_type (id)
GO
Adding default constraint will affect existing rows if you add new not nullable column to table.
ALTER TABLE group
ADD group_type INT NOT NULL
CONSTRAINT DK_group_type DEFAULT 5
GO
----------------------------------------------
DepartmentCode varchar(30) AllowNulls
----------------------------------------------
Does anyone know how to change the datatype of a column in SQL 2008? This is the column I want to alter but when I try this query,
ALTER TABLE SystemDepartment ALTER COLUMN DepartmentCode smallint NOT NULL
I get the following error:
Msg 5074, Level 16, State 1, Line 1
The object 'PK_SystemDepartment' is dependent on column
'DepartmentCode'. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE
ALTER COLUMN DepartmentCode failed because one or more objects access
this column.
My question is how to force my query to cope with it? and I also would like to set this column as primary key and identity
You will first need to drop Primary Key constraint.
ALTER TABLE SystemDepartment DROP CONSTRAINT PK_SYSTEMDEPARTMENT
Then only you can ALTER that column.
You can not force existing column to identity. In this case you will need to add new column with identity and then do sp_rename to old name.
If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]
For more info see the comments by the brilliant Aaron Bertrant on this answer.
Try this ,
as you told you are getting primary key constraint error , 1st you have to drop the primary key and use the following query ,
ALTER TABLE SystemDepartment MODIFY DepartmentCode int(3)
Thanks,
Venkat.
I am student of RDBMS.
I have very basic question let say I have one existing Table in SQL server. What will be script to alter table.
Drop Column 'RowId' if exist.
Drop contraint if exist.
Add one new column 'RowId' into table.
Make this column as primary key.
Autoincrement type int.
In SQL Server 2005 or newer, you could use this script:
-- drop PK constraint if it exists
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')
ALTER TABLE dbo.YourTable
DROP CONSTRAINT PK_YourTable
GO
-- drop column if it already exists
IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))
ALTER TABLE dbo.YourTable DROP COLUMN RowId
GO
-- add new "RowId" column, make it IDENTITY (= auto-incrementing)
ALTER TABLE dbo.YourTable
ADD RowId INT IDENTITY(1,1)
GO
-- add new primary key constraint on new column
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (RowId)
GO
Of course, this script may still fail, if other tables are referencing this dbo.YourTable using foreign key constraints onto the pre-existing RowId column...
Update: and of course, anywhere I use dbo.YourTable or PK_YourTable, you have to replace those placeholder with the actual table / constraint names from your own database (you didn't mention what they were, in your question.....)
Note: this answer was added before questions update
Add new column (note: you can only have one IDENTITY column per table)
Drop old primary key
Add new primary key
Drop old column if needed
Sample script:
CREATE TABLE whatever (
OldPKColumn uniqueidentifier NOT NULL,
CONSTRAINT PK_whatever PRIMARY KEY (OldPKColumn)
)
ALTER TABLE whatever
ADD RowId int NOT NULL IDENTITY (1,1);
ALTER TABLE whatever
DROP CONSTRAINT PK_whatever;
ALTER TABLE whatever WITH CHECK
ADD CONSTRAINT PK_whatever PRIMARY KEY CLUSTERED (RowId);
ALTER TABLE whatever
DROP COLUMN oldPKcolumn;
And a random thought... are you trying to reset an IDENTITY column?
If so, then use DBCC CHECKIDENT
Just a comment to improve these great answers (can't use comments yet - I'm one reputation point away from that privilege) and as future reference for myself:
A new IDENTITY (autonumber) column can be added and made the primary key in a single statement as well:
ALTER TABLE [TableName] ADD [ColumnName] int IDENTITY PRIMARY KEY;
I prefer not to bother with constraint names when it doesn't help.
You can specify seed (and increment) values between parantheses after the IDENTITY keyword.