Add nullable column to SQL Server with default value of null - sql

I want to add a nullable boolean column to an existing table with default value of null.
I have used this bit of script but it does not set the default value to null. it sets it to 0 instead.
ADD newColumnName BIT NULL
CONSTRAINT DF_tableName_newColumnName DEFAULT(null)

I just ran your example code snippet on my SQL Server 2008 R2 instance and then inserted a record. It initialized the column to null, as expected. The next step would be to post the alter statement and the insert statement that you used.
I used:
alter table tmp1 Add newColumnName bit null CONSTRAINT DF_tableName_newColumnName DEFAULT(null)
insert into tmp1(emp_id) values(9999)
select * from tmp1
After running the above, I used SQL Server Management Studio "Design" action to examine the properties of the new column. It showed that the "Default Value or Binding" was indeed (Null) as expected.

Related

Liquibase sets DEFAULT 0 for BIT

I add the following column in a table:
alter table my_table
add no_default bit null;
When I let Liquibase make a diff, it generates the following change:
ALTER TABLE my_table ADD no_default BIT DEFAULT 0 NULL;
As you see, it sets false (0) as default value although the column does not define it.
Is this an error or is there a way to prevent this?
// Edit: I am using a MariaDB 10.2 database.

Cannot add NOT NULL constraint [duplicate]

So I want to change a column in my SQL Server database to not allow nulls, but I keep getting an error. this is the sql statement I am using:
alter table [dbo].[mydatabase] alter column WeekInt int not null
and this is the error I am getting :
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'WeekInt', table 'CustomerRadar.dbo.tblRWCampaignMessages'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
I'm pretty sure my sql is right, and there are no nulls currently in the column I am trying to change so I am really not sure as to what is causing the problem. Any ideas? I'm stumped.
Clearly, the table has NULL values in it. Which you can check with:
select *
from mydatabase
where WeekInt is NULL;
Then, you can do one of two things. Either change the values:
update mydatabase
set WeekInt = -1
where WeekInt is null;
Or delete the offending rows:
delete from mydatabase
where WeekInt is null;
Then, when all the values are okay, you can do the alter table statement.
If you are trying to change a column to not null, and you are getting this error message, yet it appears the column has no nulls, ensure you are checking for is null and not = null (which gives different results).
Select * from ... where column is null
instead of
Select * from ... where column = null
I am adding this because it tripped me up and took a while to resolve.
This will work. You should send a default value, then it will change all the previous record to -1 in this example.
alter table [dbo].[mydatabase] alter column WeekInt int not null DEFAULT '-1';

Python pyODBC : Issue inserting into a sql server table with an identity column

An INSERT statement that was created with Python gives me an error when I execute and commit it. I have taken a copy of the statement from Python and run it myself in SQL SERVER and it works fine there. The table I am trying to insert into has an identity column. When Python trys to execute it will give me an error saying what is below when I exclude the identity column in the statement
Table looks like this MY_TABLE ( ID INT IDENTITY(1,1) NOT NULL, A INT, B INT)
INSERT INTO MY_TABLE (A, B) VALUES(VALUE_A, VALUE_B);
"('23000', "[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert the value NULL into column 'MY_IDENTITY_COLUMN', table 'MY_TABLE'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)")"
But when I try to include the value for the Identity column (I don't want to do this) I get the following error which makes sense as it's an identity column that we let the table auto-increment
"Cannot insert explicit value for identity column in table 'MY_TABLE' when IDENTITY_INSERT is set to OFF."
When I run the query in SQL SERVER the table fills the value for the Identity Column itself and auto-increments but for some reason when I run the statement in Python it does not do this and tries to pass a NULL
SQL SERVER version: 10.50.6560.0
Recognising it's a little late but... I had the same problem recently using some old program and ODBC. The solution was to create a View in SQL Server with only the columns required (i.e. A and B in your case) and then insert into that View.
A little hard to tell without your code, but here is an example.
In database create a test table
CREATE TABLE dbo.test(
ID INT IDENTITY NOT NULL PRIMARY KEY,
Name VARCHAR(40) NOT NULL
);
Then in Python specify the columns you are inserting into
import pyodbc
warecn = pyodbc.connect("Your Connection Stuff")
Inscursor = warecn.cursor()
Inscursor.execute("Insert into dbo.test(name) values ('This'), ('is'), ('a'), ('test')")
Inscursor.commit()
Inscursor.close()
del Inscursor
warecn.close()

SQL SET DEFAULT not working in MS Access

Possible Duplicate:
DEFAULT clause in ALTER TABLE statement resulting in syntax error
I am trying to execute the following statement using a SQL query within MS Access;
ALTER TABLE [table] ALTER COLUMN [column] SET DEFAULT 'default value'
However, I get a dialog displaying the error Syntax error in ALTER TABLE statement.
And when I click OK it highlights the word DEFAULT. I also tried the following statement;
ALTER TABLE [table]
ADD CONSTRAINT [Default] DEFAULT 'default value' FOR [column]
And I get another error Syntax error in CONSTRAINT clause.
What is the correct syntax for setting a default value in MS Access? The db file is Access 2003 format.
Support for DEFAULT was included in Access DDL with Jet 4 (Access 2000). However it can only be used in DDL executed from an ADO connection.
This worked with Access 2007.
CurrentProject.Connection.Execute "ALTER TABLE MyTable " & _
"ALTER COLUMN field2 SET DEFAULT ""foo"";"
Note if your db file is Access 97 or earlier, you won't be able to set a field DEFAULT value from DDL.
It seems, there would be Constraint issue with your column. Although following DDL statement is the correct way.
ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES'
Reference

Creating a sequence on an existing table

How can I create a sequence on a table so that it goes from 0 -> Max value?
I've tried using the following SQL code, but it does not insert any values into the table that I am using:
CREATE SEQUENCE rid_seq;
ALTER TABLE test ADD COLUMN rid INTEGER;
ALTER TABLE test ALTER COLUMN rid SET DEFAULT nextval('rid_seq');
The table I am trying to insert the sequence in is the output from another query. I can't figure out if it makes more sense to add the sequence during this initial query, or to add the sequence to the table after the query is performed.
Set the default value when you add the new column:
create sequence rid_seq;
alter table test add column rid integer default nextval('rid_seq');
Altering the default value for existing columns does not change existing data because the database has no way of knowing which values should be changed; there is no "this column has the default value" flag on column values, there's just the default value (originally NULL since you didn't specify anything else) and the current value (also NULL) but way to tell the difference between "NULL because it is the default" and "NULL because it was explicitly set to NULL". So, when you do it in two steps:
Add column.
Change default value.
PostgreSQL won't apply the default value to the column you just added. However, if you add the column and supply the default value at the same time then PostgreSQL does know which rows have the default value (all of them) so it can supply values as the column is added.
By the way, you probably want a NOT NULL on that column too:
create sequence rid_seq;
alter table test add column rid integer not null default nextval('rid_seq');
And, as a_horse_with_no_name notes, if you only intend to use rid_seq for your test.rid column then you might want to set its owner column to test.rid so that the sequence will be dropped if the column is removed:
alter sequence rid_seq owned by test.rid;
In PostgreSQL:
UPDATE your_table SET your_column = nextval('your_sequence')
WHERE your_column IS NULL;
I'm not fluent in postgresql so I'm not familiar with the "CREATE SEQUENCE" statement. I would think, though, that you're adding the column definition correctly. However, adding the column doesn't automatically insert data for existing rows. A DEFAULT constraint is for new rows. Try adding something like this afterwards to populate data on the existing rows.
DECLARE #i Int
SET #i = 0
SET ROWCOUNT 1
WHILE EXISTS (SELECT 1 FROM test WHERE rid IS NULL) BEGIN
UPDATE test SET rid = #i WHERE rid IS NULL
END
SET ROWCOUNT 0