Change length of column of table which have dependencies - sql

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.

Related

Error in changing column length in Postgres

I am trying to change the column size from 100 to 150 varchar data type using following query:
alter table data_warehouse.tbl_abc
alter column first_nm varchar(150) null;
Getting the following error:
SQL Error [42601]: ERROR: syntax error at or near "varchar"
Position: 77
The syntax is a bit different, so try this:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm type varchar(120);
The error in your syntax is that you missed a TYPE keyword:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150);
and if you have a NOT NULL constraint you want to remove, add a new ALTER COLUMN inside the same ALTER TABLE statement:
ALTER TABLE data_warehouse.tbl_abc
ALTER COLUMN first_nm TYPE varchar(150),
ALTER COLUMN first_nm DROP NOT NULL;
for reference look here: https://www.postgresql.org/docs/current/sql-altertable.html
Edit: as in the comment, if you have a view which involves the same column, drop it and re-create it under transaction:
BEGIN TRANSACTION;
DROP VIEW [...];
ALTER TABLE [...];
CREATE VIEW [...];
COMMIT;
Be aware that to alter a table, you must acquire an exclusive lock on it, so during the whole process, all the queries over the same table and on the views of the table are locked, also if they don't read from the altered column (because the whole table is locked) - use with caution in production environment

Changing column Datatype from date to datetime without removing existing values in MSSql and Oracle sql server [duplicate]

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);

How to add a new column and a constraint in one go?

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;

Can't ALTER TABLE in ACCESS 2012

I'm trying to alter the table of an access database. I keep getting a syntax error for something I think should be pretty simple.
Here is what I tried to do and the error I am getting.
yes you have syntax error as what access tells you, try this one
ALTER TABLE EMP_2 ADD COLUMN EMP_PCT NUMBER(4);
ALTER TABLE EMP_2 ADD COLUMN PROJ_NUM CHAR(3);
the syntax
ALTER TABLE table {ADD {COLUMN field type[(size)] [NOT NULL] [CONSTRAINT index] |
ALTER COLUMN field type[(size)] |
CONSTRAINT multifieldindex} |
DROP {COLUMN field I CONSTRAINT indexname}}
ALTER TABLE statement

In SQL Server 2005, how do I set a column of integers to ensure values are greater than 0?

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