vsdbcmd.exe generate drop constraint instructions without constraint name - sql-server

When generating a diff script between two dbschema with vsdbcmd.exe, I sometime obtain an unexpected output, containing some drop constraint without the name of the constraint :
GO
PRINT N'Dropping On column: ColumnName ...';
GO
ALTER TABLE TableName DROP CONSTRAINT ;
In our schema, this column has a default value constraint, with an auto generated name. I expected vsdbcmd.exe to generate a valid ALTER TABLE sql statement, as specified in the msdn library :
ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name DROP { [ CONSTRAINT ] constraint_name | COLUMN column_name }
Do you have any idea of what could prevent vsdbcmd.exe to generate a valid sql statement ?

This issue only occurs when the constraint has a generated name. Explicitly named constraint are not impacted.
Therefore, this solution is to name every constraint.

Related

Alter column length with or without data in table

Its about ORACLE (PL/SQL) script. I am not very familiar with databse to be honest.
I want to alter the length of a string in a column from 30 to 60. It is not null column.
If the table is empty and I run following script then it works:
alter table [TABLE_NAME] add ( NEW_COLUMN NVARCHAR2(60) DEFAULT 'null' NOT NULL );
/
alter table [TABLE_NAME] DROP CONSTRAINT PK_[TABLE_NAME];
/
begin
for rec in ( select * from [TABLE_NAME] )
loop
update [TABLE_NAME] set NEW_COLUMN =rec.OLD_COLUMN where Name_ID=rec.Name_ID;
end loop;
end;
/
alter table [TABLE_NAME] drop column OLD_COLUMN;
/
alter table [TABLE_NAME] rename column NEW_COLUMN to OLD_COLUMN;
/
alter table [TABLE_NAME] add CONSTRAINT PK_[TABLE_NAME] PRIMARY KEY(Name_ID);
/
But if the table has values then this script does not work.
It gives error: Cannot drop constraint - nonexistent constraint
However, if I remove lines about constraints (second and second last) then it works.
Now I don’t know if the table will be empty or it will have data so I need a script that can work in both the situations. Can anyone help please?
Following script for creating table:
CREATE TABLE TABLE_NAME
(
Name_ID NVARCHAR2(7) NOT NULL,
OLD_COLUMN NVARCHAR2(30) NOT NULL,
CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, OLD_COLUMN)
)
/
So while creating table it puts the primary key constraints but while updating table it drops this constraints somehow. I am simplyfying the sitation here. The tables are updates through java code. What I need to do is make a script that work in both situations - with data or just after creating table and modifying the column.
The following script works for me, regardless of whether the insert statement is present or not (ie. the table has or has not data):
CREATE TABLE TABLE_NAME
(
Name_ID NVARCHAR2(7) NOT NULL,
OLD_COLUMN NVARCHAR2(30) NOT NULL,
CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, OLD_COLUMN)
);
insert into table_name (name_id, old_column)
values ('test', 'test_old_col');
commit;
alter table table_name add (new_column nvarchar2(60) default 'null' not null);
update table_name set new_column = old_column;
commit;
alter table table_name drop constraint PK_TABLE_NAME;
alter table table_name drop column old_column;
alter table table_name rename column new_column to old_column;
alter table TABLE_NAME add CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, old_column);
drop table table_name;
I have assumed that you meant to recreate the primary key with the old_column in it, otherwise you would be unable to recreate it if there are any duplicate values present in the name_id column.
As an alternative, you can save the old data and create a new table with new parameters. Then insert the old values.
In SQL Server Management Studio:
"your database" => task => generatescripts => select specific database object => "your table" => advanced => types of data to script - schema and data => generate

AND operator in DB2 constraints

I am trying to add following constraint to my DB2 table but it gives error.
ALTER TABLE Table_name ADD CONSTRAINT VALID_BINDING
CHECK((LOWER(REQ_BINDING) IN ('http-post','http-redirect'))
AND ((LOWER(RESP_BINDING) IN ('http-post','http-redirect')));
Is this a valid query. Can I use AND operator in it?
Isn't it about parentheses?
ALTER TABLE Table_name ADD CONSTRAINT VALID_BINDING
CHECK(
LOWER(REQ_BINDING) IN ('http-post','http-redirect') AND
LOWER(RESP_BINDING) IN ('http-post','http-redirect')
);

How to set a default value for an existing column

This isn't working in SQL Server 2008:
ALTER TABLE Employee ALTER COLUMN CityBorn SET DEFAULT 'SANDNES'
The error is:
Incorrect syntax near the keyword 'SET'.
What am I doing wrong?
This will work in SQL Server:
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn
cannot use alter column for that, use add instead
ALTER TABLE Employee
ADD DEFAULT('SANDNES') FOR CityBorn
The correct way to do this is as follows:
Run the command:
sp_help [table name]
Copy the name of the CONSTRAINT.
Drop the DEFAULT CONSTRAINT:
ALTER TABLE [table name] DROP [NAME OF CONSTRAINT]
Run the command below:
ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
Hoodaticus's solution was perfect, thank you, but I also needed it to be re-runnable and found this way to check if it had been done...
IF EXISTS(SELECT * FROM information_schema.columns
WHERE table_name='myTable' AND column_name='myColumn'
AND Table_schema='myDBO' AND column_default IS NULL)
BEGIN
ALTER TABLE [myDBO].[myTable] ADD DEFAULT 0 FOR [myColumn] --Hoodaticus
END
There are two scenarios where default value for a column could be changed,
At the time of creating table
Modify existing column for a existing table.
At the time of creating table / creating new column.
Query
create table table_name
(
column_name datatype default 'any default value'
);
Modify existing column for a existing table
In this case my SQL server does not allow to modify existing default constraint value. So to change the default value we need to delete the existing system generated or user generated default constraint. And after that default value can be set for a particular column.
Follow some steps :
List all existing default value constraints for columns.
Execute this system database procedure, it takes table name as a parameter. It returns list of all constrains for all columns within table.
execute [dbo].[sp_helpconstraint] 'table_name'
Drop existing default constraint for a column.
Syntax:
alter table 'table_name' drop constraint 'constraint_name'
Add new default value constraint for that column:
Syntax:
alter table 'table_name' add default 'default_value' for 'column_name'
cheers #!!!
First drop constraints
https://stackoverflow.com/a/49393045/2547164
DECLARE #ConstraintName nvarchar(200)
SELECT #ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
WHERE NAME = N'__ColumnName__'
AND object_id = OBJECT_ID(N'__TableName__'))
IF #ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + #ConstraintName)
Second create default value
ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]
ALTER TABLE [dbo].[Employee] ADD DEFAULT ('N') FOR [CityBorn]
in case a restriction already exists with its default name:
-- Drop existing default constraint on Employee.CityBorn
DECLARE #default_name varchar(256);
SELECT #default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + #default_name);
-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;
You can use following syntax, For more information see this question and answers : Add a column with a default value to an existing table in SQL Server
Syntax :
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
WITH VALUES
Example :
ALTER TABLE SomeTable
ADD SomeCol Bit NULL --Or NOT NULL.
CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is
autogenerated.
DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.
Another way :
Right click on the table and click on Design,then click on column that you want to set default value.
Then in bottom of page add a default value or binding : something like '1' for string or 1 for int.
Just Found 3 simple steps to alter already existing column that was null before
update orders
set BasicHours=0 where BasicHours is null
alter table orders
add default(0) for BasicHours
alter table orders
alter column CleanBasicHours decimal(7,2) not null
Try following command;
ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address
ALTER TABLE tblUser
ADD CONSTRAINT DF_User_CreatedON DEFAULT GETDATE() FOR CreatedOn
Like Yuck's answer with a check to allow the script to be ran more than once without error. (less code/custom strings than using information_schema.columns)
IF object_id('DF_SomeName', 'D') IS NULL BEGIN
Print 'Creating Constraint DF_SomeName'
ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
END

How to delete a primary key which doesn't have a name?

I am using SQL Server. Is there a way to drop the primary key which doesn't have a name?
It does have a name. Even if you don't name it explicitly SQL Server will auto create a name prefixed PK and based on the table name and the object_id of the constraint.
You can use the following query to see what it is.
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_SCHEMA='dbo' AND TABLE_NAME='T'
The constraint name is required in the grammar for the DROP CONSTRAINT operation
ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name
{
....
DROP
{
[ CONSTRAINT ] constraint_name
[ WITH ( <drop_clustered_constraint_option> [ ,...n ] ) ]
| COLUMN column_name
} [ ,...n ]
Primary key always has a name. If you didn't specify it in 'create table' or 'alter table' statement, the key name is auto-generated.
In the query bellow replace X with the name of your table and run the script.
It will drop the primary key.
declare #TableName sysname = 'X'
declare #PrimaryKeyName sysname = (
select name
from sys.key_constraints
where type = 'PK' and parent_object_id = object_id(#TableName))
execute ('alter table ' + #TableName + ' drop constraint ' + #PrimaryKeyName)
It is always a good idea to specify explicit names for constraints, because if you run 'create/alter table' script on different databases, all of them will have different constraint name created.
Later, when you need to delete the constraints you need to run this workaround script, instead just running simple 'alter table drop constraint' statement.
CREATE TABLE #Tempbox (Id int primary key identity(1,1), Name varchar(200) unique)
creating a table with column Id, and name, notice it doesn't have constraint name.
Well, if you don't set contraint name for column, sql server provides their own default unique constraint name to constraint like primary key, unique and so on.
1. Let's insert some value in our #Tempbox table
1. insert into #tempbox values ('Abc')
2. insert into #tempbox values ('Abc')
unique key violation error shown by sql server along with constraint name.
**Msg 2627, Level 14, State 1, Line 5
Violation of UNIQUE KEY constraint **'UQ__#Tempbox__737584F6A146D511'**. Cannot insert duplicate key in object 'dbo.#Tempbox'. The duplicate key value is (dsaf).
The statement has been terminated.**
you got the constraint name now.. which is 'UQ__#Tempbox__737584F6A146D511'
now let's drop the column with constraint. Remember you can't drop a column if it is using a constraint so in order to drop that column you will have to drop first constraint and after column.
ALTER TABLE #Tempbox drop constraint UQ__#Tempbox__737584F6A146D511; -- constraint is dropped
now drop the column
alter table #tempbox drop column Name
Now use the same procedure for primary key column
INSERT INTO #Tempbox (Id, Name) VALUES (1,'Abc')
INSERT INTO #Tempbox (Id, Name) VALUES (1,'Abc')
Error :
Msg 2627, Level 14, State 1, Line 3
Violation of PRIMARY KEY constraint **'PK__#Tempbox__3214EC07B3D09900'**. Cannot insert duplicate key in object 'dbo.#Tempbox'. The duplicate key value is (1).
The statement has been terminated.
drop constraint and drop column.
Another way to find the constraint name..
USE Adventure
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_SCHEMA='pERSON' AND TABLE_NAME='PERSON'

Syntax needed for adding constraints to fields

In Microsoft SQL Server, I want to alter a field to "NOT NULL" AND DEFAULT ''.
I've already issued the following two commands:
ALTER TABLE USR ADD Country Varchar(128)
UPDATE USR SET Country=''
Now I need
1. ALTER TABLE USR ADD CONSTRAINT CountryIsNotNull something
2. ALTER TABLE USR ADD CONSTRAINT CountryDefault default ''
You should be able to google it however here is the syntax:
ALTER TABLE USR
ALTER COLUMN Country varchar(128) NOT NULL
go
ALTER TABLE USR
ADD CONSTRAINT df_usr_conuntry_default DEFAULT '' for Country
go
You could have done the whole thing in one line though with the following:
alter table USR
add Country varchar(128) not null default '' with values

Resources