cannot change null to not null - sql

The column name on table [dbo].[payment_info] must be changed from NULL to NOT NULL. If the table contains data, the ALTER script may not work.
To avoid this issue, you must add values to this column for all rows or mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
CREATE TABLE [dbo].[payment_info]
(
[name] VARCHAR (50) NOT NULL,
[card_no] VARCHAR (50) NULL,
[card_type] VARCHAR (50) NOT NULL,
[tel_no] VARCHAR (50) NULL,
[mob_no] VARCHAR (50) NULL,
[address] VARCHAR (MAX) NULL
);
I cannot change NULLto NOT NULL; when I update it's showing the above warning.
I am using visual studio 2013 asp.net and c#.

If table already exists and is fulfilled with data, you have to update all NULLs in column you want to change on some value which is not NULL. Then ALTER command should work wthout warnings and/or errors.

I am not really sure if I understood your problem correctly, but the warning says it all - you can't switch column to not nullable, if there are nulls already in the column.
You have to update and set some values to empty entries or set DEFAULT value
EDIT:
You should try first:
select *
from [dbo].[payment_info]
where name is null
and check if there are any problems

Right-click on your table in server explorer and click "new query". Type:
ALTER TABLE
table
ALTER COLUMN
column
int NOT NULL;

This error is produced by SSDT. This will happen if you have an existing table and you would like to add a new non-nullable column to it. In order to do so, you must have a default for this new column (the default can be some temporary value).
CREATE TABLE [dbo].[payment_info]
(
[WhateverColumn] VARCHAR (50) NOT NULL DEFAULT 'Foo',
-- and so on
);
If you want to change the default to a more meaningful value, you can write the script to update the table and set the column's value to a more meaningful value in a post deployment. In post deployment you can also now drop the default since it was temporary:
ALTER TABLE WhateverTable
ALTER COLUMN WhateverColumn DROP DEFAULT;
Now your deployment will succeed.
Note: If your column is a foreign-key column, the default has to exist in the parent table even if the value is temporary.

Related

Cannot insert the value NULL into column X, column X does not allow nulls. INSERT fails.

I'm new to SQL Server and I am getting this error "Cannot insert the value NULL into column 'Occupied', table 'DBProjectHamlet.dbo.tblGrave'; column does not allow nulls. INSERT fails. The statement has been terminated."
This is my code for the insert followed by the code to create the table
INSERT INTO tblGrave (GraveName)
SELECT Grave
FROM tblPlotsandOccupants
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tblGrave' AND TABLE_SCHEMA = 'dbo')
DROP TABLE dbo.tblGrave;
GO
CREATE TABLE tblGrave
(
GraveID INT IDENTITY (1,1),
GraveName VARCHAR(MAX) NULL,
GraveTypeID INT NOT NULL,
PlotID INT NOT NULL,
Occupied BIT NOT NULL
)
I'm not trying to insert anything into column Occupied, I don't know why this is happening or how to fix it. I just want to insert values into tblGrave (GraveName). Any help would be great.
Exactly! You aren't doing anything with Occupied and that is the problem. The column is specified to be NOT NULL but has no default value. You are not inserting a value, so it gets the default. The default default is NULL, and that is not allowed.
One simple solution is:
INSERT INTO tblGrave (GraveName, Occupied)
SELECT Grave, 0
FROM tblPlotsandOccupants;
This fixes your immediate problem, but will then you will get an error on PlotId.
A more robust solution would add a default value for the NOT NULL columns and declare the rest to be nullable (the default). Something like this:
CREATE TABLE tblGrave (
GraveID INT IDENTITY (1,1) PRIMARY KEY,
GraveName VARCHAR(MAX),
GraveTypeID,
PlotID INT,
Occupied BIT NOT NULL DEFAULT 0
);
When you created your table, you defined that column as "NOT NULL" rather than allowing it to be null.
You need to either allow "Occupied" to be null, set a default value, or define the value that you want upon inserting.
You can even set the value to be ' ' which is blank but isn't null.
EDIT
Note #Gordon's answer for sql examples.

MS SQL explicitly using "default defaults" on NOT NULL fields - why?

I stumbled upon this definition:
CREATE TABLE dbo.whatever (
[flBlahBlah] BIT DEFAULT ((0)) NOT NULL,
[txCity] NVARCHAR (50) DEFAULT ('') NOT NULL,
[cdFrom] VARCHAR (10) DEFAULT ('') NOT NULL
);
I can't think of a reason to add those default values. Not null string is defaulted to '' and bit is defaulted to 0. Is there a reason for defining these default values? Am I missing something? Is this in some best practice handbook I'm not aware of?
I'd just use:
CREATE TABLE dbo.whatever (
[flBlahBlah] BIT NOT NULL,
[txCity] NVARCHAR (50) NOT NULL,
[cdFrom] VARCHAR (10) NOT NULL
);
The database is in MS SQL Server 2012, now migrating to Azure Database.
For example you create table from a first batch of your question. Then insert value like this
INSERT INTO dbo.whatever (flBlahBlah) VALUES (1)
You will get 1 row dbo.whatever
flBlahBlah txCity cdFrom
1
So if you "forget" to insert in one of the column with default values determined - SQL Server will take care of them.
It is very useful when you got table, in which you need to insert new field. With default value determined you don't need to change SP/query's/other stuff that works with this table.

Can not add a column to existing table

I have a table viz. expenses with three columns as under
ExpenseId int NOT NULL,
ExpenseName varchar(50) NOT NULL,
Invalid bit NOT NULL
To add a new column (OldCode char(4) not null), I used design feature for tables in Microsoft SQL Server Management Studio. But I get following error
'Expenses' table
- Unable to modify table. Cannot insert the value NULL into column 'OldCode', table 'TransportSystemMaster.dbo.Tmp_Expenses'; column does not allow nulls. INSERT fails. The statement has been terminated.
Incidentally I have been able to add same column with same specifications to other tables of the same database.
Any help?
Your Table Consist of Existing Records
and you are pushing a new column of type NOT NULL.
so for older records the data have to be something.
try something like this
ALTER TABLE MY_TABLE ADD Column_name INT NULL
GO
UPDATE MY_TABLE <set valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN Column_name INT NOT NULL
GO
Since OldCode is NOT NULL, you should specify a default value for it.
when you have some rows on your table you can't add a column that is not nullable you should provide a default value for it
Alter Table table_name add OldCode int not null DEFAULT(0);
You have to specify values for all the 4 fields of the table, its purely because, while designing the table you set the definition of the columns to be not null. Again you are adding a new column called OldCode and setting to be not null, all ready existing records hasn't got a value. So that is the reason its complains

SQL Server - Default value

I don't know if this is possible, but i would like to know if when we create a table on which a field has a default value, we can make this Default value get the value of another column upon row insertion.
Create Table Countries (
ID Int Not Null Identity(1,1),
CountryCode Char (2) Not Null,
Country Varchar (50) Not Null,
CountryRegion Varchar (50) Null Default ('Country'),
Nationality Varchar (75) Not Null Default ('Not Known'),
InsertDate Datetime2 Not Null Default Getdate(),
Constraint PK_CountryCode Primary Key (CountryCode));
On CountryRegion field, I could place an ('Unknown') default value, but like I said, is it possible this field gets by default the value inserted on Country field if nothing is placed on it?
Using a trigger would do - UPDATE a column right after insertion
CREATE TRIGGER CountriesTrigger ON Countries AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE Countries
SET
Countries.CountryRegion = inserted.Country
FROM Countries, inserted
WHERE Countries.ID = inserted.ID
AND inserted.CountryRegion is null
END
I think there is no easy of doing this at TABLE level. There are some workarounds to do this :
1. If you are using stored procs then you can write your logic over there.
2. Trigger is also an option but overhead in terms of execution.
Thanks.

Can I add a not null column without DEFAULT value

Can I add a column which is I specify as NOT NULL,I don't want to specify the DEFAULT value but MS-SQL 2005 says:
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'test' cannot be added to non-empty table 'shiplist' because it does not satisfy these conditions.
If YES, please let me know the syntax, if No please specify the reason.
No, you can't.
Because if you could, SQL wouldn't know what to put as value in the already existing records. If you didn't have any records in the table it would work without issues.
The simplest way to do this is create the column with a default and then remove the default.
ALTER TABLE dbo.MyTable ADD
MyColumn text NOT NULL CONSTRAINT DF_MyTable_MyColumn DEFAULT 'defaultValue'
ALTER TABLE dbo.MyTable
DROP CONSTRAINT DF_MyTable_MyColumn
Another alternative would be to add the column without the constraint, fill the values for all cells and add the constraint.
Add the column to the table, update the existing rows so none of them are null, and then add a "not null" constraint.
No - SQL Server quite reasonably rejects this, because it wouldn't know what value existing rows should have
It's easy to create a DEFAULT at the same time, and then immediately drop it.
I use this approach to insert NOT NULL column without default value
ALTER TABLE [Table] ADD [Column] INT NULL
GO
UPDATE [Table] SET [Column] = <default_value>
ALTER TABLE [Table] ALTER COLUMN [Column] INT NOT NULL
No.
Just use empty string '' (in case of character type) or 0 (if numeric), etc as DEFAULT value
No you cannot. But you can consider to specify the default value to ('')
No, you can't, as SQL Server, or any other database engines will force this new column to be null for existing rows into your data table. But since you do not allow a NULL, you are required to provide a default value in order to respect your own constraint. This falls under great sense! The DBE will not extrapolate a value for non-null values for the existing rows.
#Damien_The_Unbeliever's comment ,
Is it adding computed column? Neither question nor answer implied anything like that. In case of computed column the error states:
"Only UNIQUE or PRIMARY KEY constraints can be created on computed columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require that computed columns be persisted"
OK, if to continue this guessing game, here is my script illustrating the adding of "NOT NULL" column in one "ALTER TABLE" step:
CREATE TABLE TestInsertComputedColumn
(
FirstName VARCHAR(100),
LastName CHAR(50)
);
insert into TestInsertComputedColumn(FirstName,LastName)
select 'v', 'gv8';
select * from TestInsertComputedColumn;
ALTER TABLE TestInsertComputedColumn
ADD FullName As FirstName + LastName PERSISTED NOT NULL;
select * from TestInsertComputedColumn;
--drop TABLE TestInsertComputedColumn;
I used below approach it worked for me
Syntax:
ALTER TABLE <YourTable> ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>
Example:
ALTER TABLE Tablename ADD ColumnName datetime NOT NULL DEFAULT GETDATE();
As an option you can initially create Null-able column, then update your table column with valid not null values and finally ALTER column to set NOT NULL constraint:
ALTER TABLE MY_TABLE ADD STAGE INT NULL
GO
UPDATE MY_TABLE SET <a valid not null values for your column>
GO
ALTER TABLE MY_TABLE ALTER COLUMN STAGE INT NOT NULL
GO