I am using the AdventureWorks2012 database...
I created a backup table using the SELECT INTO clause. However, I got an error message when I tried to insert data into some columns using the query below:
INSERT INTO Sales.salesorderdetails_backup
(SalesOrderID ,
OrderQty,
ProductId,
SpecialOfferId,
UnitPrice,
UnitPriceDiscount,
LineTotal)
OUTPUT inserted.*
VALUES (57123,
45,
712,
1,
15.89,
0,
45.89)
I got the error msg:
Cannot insert the value NULL into column 'rowguid', table
'AdventureWorks2014.Sales.salesorderdetails_backup'; column does not
allow nulls. INSERT fails...
When you define your table, you can specify a "not null" constraint for any column or columns. Which means that you MUST put a value in that column for any insert.
This is generally a Good Thing. For example, "not null is the default for a primary key column.
You have two choices:
1) Make sure the column in question has a value before you "Insert" (PREFERRED)
2) Do an "alter table" to drop the "not null" constraint:
ALTER TABLE MyTable ALTER COLUMN MyColumn columnType NULL
ALSO: As you probably know, NEWID() is the MSSQL function to generate a GUID for your "insert".
I finally succeeded after I added DEFAULT constraints:
ALTER TABLE Sales.salesorderdetails_backup
ADD CONSTRAINT df_date DEFAULT GETDATE() for ModifiedDate;
ALTER TABLE Sales.salesorderdetails_backup
ADD CONSTRAINT df_guid DEFAULT NEWID() FOR rowguid;
Related
I want to add a primary key constraint to an existing column on an existing table that contains data. The column is not nullable.
However, when I call
alter table mytable add primary key (mycolumn)
I get an 8111:
Msg 8111, Level 16, State 1, Line 2 Cannot define PRIMARY KEY
constraint on nullable column in table 'mytable'
Even if I call both instructions in a row:
alter table mytable alter column mycolumn INT NOT NULL;
alter table mytable add primary key (mycolumn)
I still get an 8111
- and the column description in SQL Server Management Studio confirms, that mycolumn is set to NOT NULL
What can I do this?
You need to separate your batches. It would be best to include the schema name as well.
alter table dbo.mytable alter column mycolumn INT NOT NULL;
go
alter table dbo.mytable add primary key (mycolumn);
rextester demo: http://rextester.com/TZLEWP56616
I have an invalid Column Name error when inserting a record to my SQL Server table. Here's the definition:
CREATE TABLE [dbo].[myTable]
(
[id] int IDENTITY(1, 1) NOT NULL,
[person_name] varchar(255) NOT NULL,
[modified_By] varchar(255) NOT NULL
)
ON [PRIMARY] WITH (DATA_COMPRESSION = NONE);
GO
And insert
INSERT INTO myDB.dbo.myTable (id, person_name, modified_By)
VALUES (1, 'Aishwarya', 'admin')
But I get the following error upon execution:
Lookup Error - SQL Server Database Error: Invalid column name
'modified_BY'.
I can SELECT from the column fine. The only thing I've noticed in error is that "BY" is capitalized, contrary to the table definition. Any ideas?
UPDATE: Updating all the syntax errors, apologeez
Is your database set to a case sensitive collation? You can check by running this query:
SELECT DATABASEPROPERTYEX('<Insert Database Name>', 'Collation') SQLCollation;
Case insensitive collations usually have CI in the name, such as SQL_Latin1_General_CP1_CI_AS.
Where as case sensitive collation might be something like Latin1_General_BIN.
If the database has a case sensitive collation, then the capitalization in the T-SQL must match the column definition.
Your post here doesn't include the modified_BY capitalization in the insert statement, so double check that. If it's capitalized there properly, then check if there are any triggers on the table that might have the improper spelling.
In your INSERT statement do not supply a value for your IDENTITY column "Id". It should look like:
INSERT INTO myDB.dbo.myTable
(person_name, modified_By)
VALUES ('Aishwarya', 'admin')
Not an answer anyone wants to hear, but our DBA dropped and recreated the table (which had triggers set on it) and this has resolved the issue.
I need to design a table in SQL Server having some columns, one of these columns (ID column and use sequential uniqueidentifier) should automatically populate its data when inserting other column data.
The values of the ID column should be generated automatically when insertion happens.
Please help me to do this, any help is appreciated.
NB: I am new to this step by step approach will be more helpful
Just create a table with a column ID of datatype uniqueidentifier and set it's default value to newsequentialid():
Then, when you go insert rows into that table, just omit the ID column from the list of columns you're inserted values into:
INSERT INTO dbo.YourTable(ColA, ColB, ....., ColX)
VALUES(.., .. ,. ...)
If you don't explicitly insert a value into ID, the default specification (newsequentialid()) will be used .
As per Marc_s's comment, you should use NEWSEQUENTIALID()
CREATE TABLE myTable (ColumnA uniqueidentifier DEFAULT NEWSEQUENTIALID());
See NEWSEQUENTIALID (Transact-SQL)
I have a table [Product] with a column [CreateTime] datetime null, and is has some data already.
How can I set the column [CreateTime] 's default value to getdate(), and make the new added data to have a default value getdate() for column [CreateTime].
You cannot change a default - you will need to first drop it, and then recreate it.
In order to drop it, you need to know its name, and then use
ALTER TABLE dbo.Product
DROP CONSTRAINT yourOldDefaultConstraint
Once you've done that, you can add a new default constraint, and in order to apply it to existing rows, use the "WITH VALUES" part:
ALTER TABLE dbo.Product
ADD CONSTRAINT NewDefaultConstraintName
DEFAULT GetDate() FOR CreateTime WITH VALUES
Oops - sorry, the "WITH VALUES" only seems to work if you create a DEFAULT constraint at the time you create the table, or if you add the column - it doesn't seem to get applied to an existing column.
In this case you would just have to follow your ALTER TABLE statement with something like this:
UPDATE dbo.T_Product
SET CreateTime = GETDATE()
WHERE CreateTime IS NULL
That should do the trick, too!
Marc
I have a table that has several nullable integer columns. This is undesirable for several reasons, so I am looking to update all nulls to 0 and then set these columns to NOT NULL. Aside from changing nulls to 0, data must be preserved.
I am looking for the specific SQL syntax to alter a column (call it ColumnA) to "not null". Assume the data has been updated to not contain nulls.
Using SQL server 2000.
First, make all current NULL values disappear:
UPDATE [Table] SET [Column]=0 WHERE [Column] IS NULL
Then, update the table definition to disallow "NULLs":
ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL
I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:
ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];
You will have to do it in two steps:
Update the table so that there are no nulls in the column.
UPDATE MyTable SET MyNullableColumn = 0
WHERE MyNullableColumn IS NULL
Alter the table to change the property of the column
ALTER TABLE MyTable
ALTER COLUMN MyNullableColumn MyNullableColumnDatatype NOT NULL
For Oracle 11g, I was able to change the column attribute as follows:
ALTER TABLE tablename MODIFY columnname datatype NOT NULL;
Otherwise abatichev's answer seemed good. You can't repeat the alter - it complains (at least in SQL Developer) that the column is already not null.
this worked for me:
ALTER TABLE [Table]
Alter COLUMN [Column] VARCHAR(50) not null;
As long as the column is not a unique identifier
UPDATE table set columnName = 0 where columnName is null
Then
Alter the table and set the field to non null and specify a default value of 0
In case of FOREIGN KEY CONSTRAINT... there will be a problem if '0' is not present in the column of Primary key table. The solution for that is...
STEP1:
Disable all the constraints using this code :
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
STEP2:
RUN UPDATE COMMAND (as mentioned in above comments)
RUN ALTER COMMAND (as mentioned in above comments)
STEP3:
Enable all the constraints using this code :
exec sp_msforeachtable #command1="print '?'", #command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
this seems simpler, but only works on Oracle:
ALTER TABLE [Table]
ALTER [Column] NUMBER DEFAULT 0 NOT NULL;
in addition, with this, you can also add columns, not just alter it.
It updates to the default value (0) in this example, if the value was null.
In my case I had difficulties with the posted answers. I ended up using the following:
ALTER TABLE table_name CHANGE COLUMN column_name column_name VARCHAR(200) NOT NULL DEFAULT '';
Change VARCHAR(200) to your datatype, and optionally change the default value.
If you don't have a default value you're going to have a problem making this change, as default would be null creating a conflict.
Making column not null and adding default can also be done in the SSMS GUI.
As others have already stated, you can't set "not null" until all
the existing data is "not null" like so:
UPDATE myTable SET myColumn = 0
Once that's done, with the table in design view (right click on
table and click "design view"), you can just uncheck the Allow
Nulls columns like so:
Still in design view with the column selected, you can see the
Column Properties in the window below and set the default to 0 in there as well like so:
Let's take an example:
TABLE NAME=EMPLOYEE
And I want to change the column EMPLOYEE_NAME to NOT NULL. This query can be used for the task:
ALTER TABLE EMPLOYEE MODIFY EMPLOYEE.EMPLOYEE_NAME datatype NOT NULL;
For the inbuilt javaDB included in the JDK (Oracle's supported distribution of the Apache Derby) the below worked for me
alter table [table name] alter column [column name] not null;
You can change the definition of existing DB column using following sql.
ALTER TABLE mytable modify mycolumn datatype NOT NULL;
First make sure the column that your changing to not does not have null values
select count(*) from table where column's_name is null
Impute the missing values. you can replace the nulls with empty string or 0 or an average or median value or an interpolated value. It depends on your back fill strategy or forward fill strategy.
Decide if the column values need to be unique or non-unique. if they need to be unique than add an unique constraint. Otherwise, see if performance is adequate or if you need to add an index.