I want to add a new column to an existing table.
I need it to emulate the enum type (in the way possible in SQL Server; with value constraints, that is).
The following doesn't work:
ALTER TABLE orders ADD [sent_to_panel] NVARCHAR(16) NULL;
ALTER TABLE orders WITH CHECK ADD CONSTRAINT [CK_orders] CHECK (([sent_to_panel]='invalidated' OR [sent_to_panel]='not_sent' OR [sent_to_panel]='sent'));
ALTER TABLE orders ADD CONSTRAINT [DF_orders_sent_to_panel] DEFAULT (N'not_sent') FOR [sent_to_panel];
ALTER TABLE orders CHECK CONSTRAINT [CK_orders];
I'm getting an error:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'sent_to_panel'.
If I execute the first command on its own, though:
ALTER TABLE orders ADD [sent_to_panel] NVARCHAR(16) NULL;
The rest goes through.
So I suppose the problem is that the column isn't actually added yet (and thus not recognized by ADD CONSTRAINT) when trying to get it all done in one go.
The question is: how to make the script work properly?
CREATE TABLE a (
b int
);
ALTER TABLE a
ADD c nvarchar(16) NULL
, CONSTRAINT check_this CHECK (c IN ('invalidated', 'not_sent', 'sent'))
, CONSTRAINT defaultify DEFAULT ('not_sent') FOR c
;
ALTER TABLE a
CHECK CONSTRAINT check_this
;
DROP TABLE a;
Related
I want to alter the existing column Site_SiteId in SQL Server to make it as not null with default value 1 but getting a syntax error:
ALTER TABLE dbo.ImagingEvents
ALTER COLUMN Site_SiteId bit NOT NULL DEFAULT 1
default is a constraint so you need to add it to the table:
ALTER TABLE dbo.ImagingEvents ADD DEFAULT 1 FOR Site_SiteId
First you need to ALTER the column:
ALTER TABLE dbo.ImagingEvents ALTER COLUMN Site_SiteId bit NOT NULL;
Note that if you have any rows that already have the value NULL you will need to UPDATE them first, before performing the ALTER.
Then, personally, I would recommend creating a named constraint, like so:
ALTER TABLE dbo.ImagingEvents ADD CONSTRAINT DF_Site_SiteId DEFAULT 1 FOR Site_SiteId;
Having named constraints, rather than the automatically named ones, is far better for transferable code.
I am trying to do this:
ALTER TABLE CompanyTransactions DROP COLUMN Created
But I get this:
Msg 5074, Level 16, State 1, Line 2
The object 'DF__CompanyTr__Creat__0CDAE408' is dependent on column 'Created'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE DROP COLUMN Created failed because one or more objects access this column.
This is a code first table. Somehow the migrations have become all messed up and I am trying to manually roll back some changed.
I have no idea what this is:
DF__CompanyTr__Creat__0CDAE408
You must remove the constraints from the column before removing the column. The name you are referencing is a default constraint.
e.g.
alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
alter table CompanyTransactions drop column [Created];
The #SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column
ALTER TABLE MySchema.MyTable ADD
MyColumn int DEFAULT NULL;
But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.
So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:
ALTER TABLE MySchema.MyTable ADD
MyColumn int NULL,
CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;
You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.
As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.
Perform followings steps to do the needful.
Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name>
drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc
When you alter column datatype you need to change constraint key for every database
alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
You need to do a few things:
You first need to check if the constrain exits in the information schema
then you need to query by joining the sys.default_constraints and sys.columns
if the columns and default_constraints have the same object ids
When you join in step 2, you would get the constraint name from default_constraints. You drop that constraint. Here is an example of one such drops I did.
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLE_NAME'
AND COLUMN_NAME = N'LOWER_LIMIT')
BEGIN
DECLARE #sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 #sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
FROM sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
IF ##ROWCOUNT = 0
BEGIN
PRINT 'DELETED Constraint on column LOWER_LIMIT'
BREAK
END
EXEC (#sql)
END;
ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
PRINT 'DELETED column LOWER_LIMIT'
END
ELSE
PRINT 'Column LOWER_LIMIT does not exist'
GO
In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:
Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");
You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.
I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".
USE [DATABASENAME]
GO
ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9]
GO
ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName]
GO
I needed to replace an INT primary key with a Guid. After a few failed attempts, the EF code below worked for me. If you hyst set the defaultValue... you end up with a single Guid a the key for existing records.
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropUniqueConstraint("PK_Payments", "Payments");
migrationBuilder.DropColumn(
name: "PaymentId",
table: "Payments");
migrationBuilder.AddColumn<Guid>(
name: "PaymentId",
table: "Payments",
type: "uniqueidentifier",
defaultValueSql: "NewId()",
nullable: false);
}
Copy the default constraint name from the error message and type it in the same way as the column you want to delete.
I had the same problem, I could not remove migrations, it would show error that something is already applied, so i changed my DB name in appsettings, removed all migrations, and then added new migration and it worked. Dont understand issue completely, but it worked
I fixed by Adding Dropping constraint inside migration.
migrationBuilder.DropForeignKey(
name: "FK_XX",
table: "TableX").
and below recreates constraint.
migrationBuilder.AddForeignKey(
name: "FK_XX",
table: "TableX",
column: "ColumnX",
onDelete: ReferentialAction.Restrict);
I've got a table named Contacts with column Title varchar(50) . Now in the middle of development I want to change the length to varchar(100) of field Title .At the moment table Contacts has over 25 dependencies (other tables, views functions).
When I run following sql statement in sql server 2008 . I am getting errors.
ALTER TABLE [Contacts ] ALTER COLUMN [Title ] varchar(100)
Error Like
Msg 5074, Level 16, State 1, Line 2
The object 'Contacts_title' is dependent on column 'title'.
And more.
you have to drop are recreate the constrains on the Contact table to do that or (sometime not really recommended ) you can temporary disable the constrain, alter the length and enable them again
--disable all constraints for the Sales.SalesOrderHeader table
ALTER TABLE [yourtable] NOCHECK CONSTRAINT ALL
--do your stuff
--do something --enable all constraints for the Sales.SalesOrderHeader table
ALTER TABLE [yourtable] CHECK CONSTRAINT ALL
You have to remove the dependence, and then create it again.
I have a Product table in which I want to create a new columns Modified_By and Modified_Date_Time. These columns do not allow nulls.
However, as the database already has data, in order to create this column, I had to defined as "allowing nulls". Then, I run a process which updated the new column. The last step was to uncheck the "Allow nulls" property, but when I tried to save the table changes, I got the following error:
'Product_Details' table
- Unable to modify table.
Cannot insert the value NULL into column 'Modified_Date_Time', table 'Vendor Products.dbo.Tmp_Product_Details'; column does not allow nulls. INSERT fails.
The statement has been terminated.
All the rows were succesfully updated with the correct value in the "Modified_By" and "Modified_Date_Time" column, so I don't know why I get this error...Anyway, it seems like a new "temporary" table was created by SQL Server 2008, because I don't have any table with the name "Tmp_Orders"
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
You have to set a default value.
ALTER TABLE Product ADD Modified_By datetime DEFAULT (GETDATE())
The default value will be set to today.
I find the interactive design is not very good at this sort of thing. It's better to simply add the constraint manually
ALTER TABLE Table_Name ALTER COLUMN Column_Name DataType NOT NULL
E.g.
ALTER TABLE MyTable ALTER COLUMN A_Column Int NOT NULL;
This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.
Thanks!
I was in error with my last comment all is good now.
You can use a check constraint on the column. IIRC the syntax for this looks like:
create table foo (
[...]
,Foobar int not null check (Foobar > 0)
[...]
)
As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to.
alter table foo
add constraint Foobar_NonNegative
check (Foobar > 0)
You can get out the text of check constraints from the system data dictionary in sys.check_constraints:
select name
,description
from sys.check_constraints
where name = 'Foobar_NonNegative'
Create a database constraint:
ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol > 0)
You can have pretty sophisticated constraints, too, involving multiple columns. For example:
ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate<EndDate OR EndDate IS NULL)
I believe you want to add a CONSTRAINT to the table field:
ALTER TABLE tableName WITH NOCHECK
ADD CONSTRAINT constraintName CHECK (columnName > 0)
That optional NOCHECK is used to keep the constraint from being applied to existing rows of data (which could contain invalid data) & to allow the constraint to be added.
Add a CHECK constraint when creating your table
CREATE TABLE Test(
[ID] [int] NOT NULL,
[MyCol] [int] NOT NULL CHECK (MyCol > 1)
)
you can alter your table and add new constraint like bellow.
BEGIN TRANSACTION
GO
ALTER TABLE dbo.table1 ADD CONSTRAINT
CK_table1_field1 CHECK (field1>0)
GO
ALTER TABLE dbo.table1 SET (LOCK_ESCALATION = TABLE)
GO
COMMIT