I have an SQL script for creating a table, i would like the default of all but a few columns to be \"\" the others require a integer default of 0
The following crea
When you create a constraint without a name, the SQL Server
automatically create internal name. It can be see in the [sys].[default_constraints]
.
For example:
DROP TABLE IF EXISTS [dbo].[StackOverflow];
CREATE TABLE [dbo].[StackOverflow]
(
[colA] INT
,[colB] INT DEFAULT(0)
,[colC] CHAR(1) DEFAULT('x')
);
GO
SELECT *
FROM [sys].[default_constraints]
WHERE [parent_object_id] = OBJECT_ID('[dbo].[StackOverflow]');
GO
You can use the name to drop the constraint.
If you have more of them, you can use one of the scripts below:
-- all suported editions
DECLARE @DynamicTSQLStataement NVARCHAR(MAX)
,@TableNameWithSchema SYSNAME;
SET @TableNameWithSchema = '[dbo].[StackOverflow]';
SELECT @DynamicTSQLStataement = STUFF
(
(
SELECT ';ALTER TABLE ' + @TableNameWithSchema + ' DROP CONSTRAINT ' + QUOTENAME([name])
FROM [sys].[default_constraints]
WHERE [parent_object_id] = OBJECT_ID('[dbo].[StackOverflow]')
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
EXEC sp_executesql @DynamicTSQLStataement;
GO
or
-- SQL Server 2016 or later
DECLARE @DynamicTSQLStataement NVARCHAR(MAX)
,@TableNameWithSchema SYSNAME;
SET @TableNameWithSchema = '[dbo].[StackOverflow]';
SELECT @DynamicTSQLStataement = STRING_AGG('ALTER TABLE ' + @TableNameWithSchema + ' DROP CONSTRAINT ' + QUOTENAME([name]), ';')
FROM [sys].[default_constraints]
WHERE [parent_object_id] = OBJECT_ID('[dbo].[StackOverflow]');
EXEC sp_executesql @DynamicTSQLStataement;
GO
When you add a default, you should use names for your constraints. This way you can later refer to those constraints by name.
ALTER TABLE [dbo].[PMIPatients] ADD CONSTRAINT [PatientFallRiskLevel_Default] DEFAULT ((0)) FOR PatientFallRiskLevel
Then you can drop it using:
ALTER TABLE [dbo].[PMIPatients] DROP CONSTRAINT [PatientFallRiskLevel_Default]
The syntax is:
ALTER TABLE [dbo].[PMIPatients] ADD CONSTRAINT NameYourConstraint DEFAULT ((0)) FOR [PatientFallRiskLevel]
ALTER TABLE [dbo].[PMIPatients] DROP CONSTRAINT NameYourConstraint