Inserting data into one column fails saying values in another column can't be null - sql-server

I can't understand this misunderstanding by SQL Server.
As you can see, I'm trying to insert into column Ordamount, but SQL Server shows me in its error message that it can't insert null into column UserID?
Declare #variable1 int =( select sum(Orr.quantity *OI.Iteprice)
from Orderrouter Orr
inner join OrdItem OI on Orr.OrdItems =OI.ItemId
where OrdId = 1)
insert into Ord (Ordamount)
values (#variable1);
Error:
Msg 515, Level 16, State 2, Line 6 Cannot insert the value
NULL into column 'UserID', table 'Example.dbo.Ord'; column does
not allow nulls. INSERT fails.
The statement has been terminated.

For columns in the Ord table that does not allow null by default, you have to provide value for, you cannot skip them. You have to provide value for UserID if it's not Nullable unless it's an identity column

I think the problem is that you only specify the amount when inserting which isn't the primary key in the table, might be an idea to show how the table looks as well. An auto increment on the id column migh solve the problem

Please use a more descriptive title.
Beside this, it seems that the Ord.UserID field is not initialized. Maybe it is not an autoincrement.
Try with this, specifying the UserId value:
INSERT into Ord values(<UserId value here>, #Varaible1)

Related

Cannot insert 'NULL' value into SQL Server column

I have a table that is filled using a stored procedure. This stored procedure uses a view that calls attributes from another databases.
To illustrate, it is something like:
ALTER PROCEDURE theSp
AS BEGIN
INSERT INTO dbo.theTable (attr1, att2, amount, attr4)
SELECT attr1, attr2, amount, attr4
FROM theView
END
The view is defined this way:
select attr1, attr2, amount, attr4
from db1.theTable
where date >='anyDate'
and the values are correctly inserted, but if the view is used this way:
select attr1, attr2, amount, attr4
from db2.theTable
where date >='anyDate'
this message is shown:
Checking identity information: current identity value '1252'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Msg 515, Level 16, State 2, Procedure theSp, Line 16
Cannot insert the value NULL into column 'amount', table 'db2.dbo.theTable'; column does not allow nulls. INSERT fails.
Note: the 'amount' attribute for db1 and db2 tables allows null but I never insert null, instead, I insert 0.
So I filtered to check whether the amount attribute is null and I did not get results, meaning there are not nulls value in the amount attribute.
Does anyone know a possible solution?
By looking at the error message that you have posted
Cannot insert the value NULL into column 'amount', table 'db2.dbo.theTable'; column does not allow nulls. INSERT fails. The statement has been terminated.
there is a Null value for amount column in `db2.dbo.theTable'. You can use ISNULL() to get rid of this issue.
If you want to see the NULL values, you gotta use query like
select * from db2.dbo.theTable where amount IS NULL
Have a look at is Null vs =Null to see why you weren't seeing those null records in your previous query.
Good to have a logger to validate the condition when it's going wrong, like printing the values before inserting

HANA SQL Script INSERT INTO with INNER JOIN can't insert values

I'm quite new to SQL and hope you can help me with my problem.
I have a table called Order_Status_Form_3 with the columns Order_ID (KEY), Customer_ID, Customer_Unique_ID, Status(KEY) and Date.
The table is filled, except for the Customer_Unique_ID Column.
To fill this Column I need to reference the Customer table where the Customer_ID is linked to the Customer_Unique_ID, so the right IDs cover the right places. When the Customer_ID in Order_Status_Form_3 equals the Customer_ID in the Customer table the given Customer_Unique_ID shall be inserted into the Customer_Unique_ID column in Order_Status_Form_3.
I tried to combine an INSERT INTO with a SELECT and INNER JOIN, but received an error message that says:
"cannot insert NULL or update to NULL: Order_ID".
I guess it's not clear for the program where to insert the values found and it tries to insert into all columns. I searched for similar problems but could not find any satisfying answers for my specific problem.
Here's the code I used:
Insert Into "HXE_109"."Order_Status_Form_3" ("Customer_Unique_ID")
Select customer."customer_unique_id"
From "HXE_109"."Customer" As customer
Inner Join "HXE_109"."Order_Status_Form_3" As OrderStatus3
On OrderStatus3."Customer_ID" = customer."customer_id"
I tried to specify the place to insert the values found by attaching a WHERE at the end, but received the same error.
Where OrderStatus3."Customer_ID" = customer."customer_id"
Does anyone know how to solve this issue and can tell me where my mistake is?
Thanks in advance for reading this long question and leaving an answer.
Edit
I tried using update but it seems like I cannot get it right.
Update "HXE_109"."Order_Status_Form_3"
Set "Customer_Unique_ID" = (Select customer."customer_unique_id"
From "HXE_109"."Customer" As customer
Inner Join "HXE_109"."Order_Status_Form_3" As OrderStatus3
On OrderStatus3."Customer_ID" = customer."customer_id")
Now I get the following error:
single row query returns more than one row
Do I need to use a Where condition here?
Sorry for my stupidity. :(
As I could follow the comments, what you want to do is running an UPDATE statement
Please check following DML command
Update "HXE_109"."Order_Status_Form_3"
Set
"Customer_Unique_ID" = customer."customer_unique_id"
From "HXE_109"."Order_Status_Form_3" As OrderStatus3
Inner Join "HXE_109"."Customer" As customer
On OrderStatus3."Customer_ID" = customer."customer_id"
If I try to explain the error messages:
"cannot insert NULL or update to NULL: Order_ID".
That is related with a field defined as NOT NULL. So in your target table ORDER_ID is defined as "not null", so in INSERT you have to provide a value for it or define it as an identity field in your HANA table definition
The second error: single row query returns more than one row
This is related with the case where SQL Engine expects a value not a set of values.
So the SELECT statement that you assign the results to Customer_Unique_ID field returns more than 1 value. In this case SQL engine raises an exception

T-SQL insert with select and extra column populated by default value

I am attempting to insert into a table using a select and adding a couple of extra columns. The extra columns have default values and one is populated by a sequence by default so not sure why I can't do:
insert into ADDRESS_HIST
select * from ADDRESS;
Getting error:
Msg 213, Level 16, State 1, Line 3
Column name or number of supplied values does not match table definition.
insert into ADDRESS_HIST
select
*,
null as [END_DATE],
getdate() as [EFFECTIVE_DATE],
next value for ADDRESS_HIST_ID_SEQ as [ADDRESS_HIST_ID]
from
ADDRESS;
Error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'ADDRESS_HIST_ID', table 'ADDRESS_HIST'; column does not allow nulls. INSERT fails.
I've tested my sequence and its working fine.
Any insight most appreciated.
Edit: I thought that the first example would be possible if the extra columns were either provided a default value or nullable. my mistake.
What is the issue with the second example? I am clearly supplying a value from a sequence for ADDRESS_HIST_ID.
The error messages have already given you the answer.
In the first case, if the number of columns of ADDRESS_HIST is different from that of ADDRESS, you have to specify the columns like
INSERT INTO TABLE_NAME
(column1, column2, column3,...columnN) VALUES
(value1, value2, value3,...valueN);
In the second case, obviously you're inserting a null value into a non-nullable column of ADDRESS_HIST.

How can I append rows from another table and also add a constant to another attribute?

I want to append rows to a table. The first attribute will be from another table, using all the rows in that table, and the other attribute will be a constant.
INSERT INTO tStoreHistory(StoreID, StoreStatusID) VALUES((Select StoreID from tStore), 1)
I get this error:
Msg 109, Level 15, State 1, Line 1
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
Am sure your insert query does not generate that error check whether any other Insert statement is present or It could be because of Trigger present in tStoreHistory table. If you have any trigger on tStoreHistory table then post the code
Between proper way to write that Insert query would be
INSERT INTO tStoreHistory(StoreID, StoreStatusID)
Select StoreID,1 from tStore
Your current Insert query will throw an exception when more than one record is returned from the sub-query (ie) when tStore table has more than one record

How can I get the result from SQL generated Identity? [duplicate]

I'm trying to get a the key-value back after an INSERT-statement.
Example:
I've got a table with the attributes name and id. id is a generated value.
INSERT INTO table (name) VALUES('bob');
Now I want to get the id back in the same step. How is this done?
We're using Microsoft SQL Server 2008.
No need for a separate SELECT...
INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');
This works for non-IDENTITY columns (such as GUIDs) too
Use SCOPE_IDENTITY() to get the new ID value
INSERT INTO table (name) VALUES('bob');
SELECT SCOPE_IDENTITY()
http://msdn.microsoft.com/en-us/library/ms190315.aspx
INSERT INTO files (title) VALUES ('whatever');
SELECT * FROM files WHERE id = SCOPE_IDENTITY();
Is the safest bet since there is a known issue with OUTPUT Clause conflict on tables with triggers. Makes this quite unreliable as even if your table doesn't currently have any triggers - someone adding one down the line will break your application. Time Bomb sort of behaviour.
See msdn article for deeper explanation:
http://blogs.msdn.com/b/sqlprogrammability/archive/2008/07/11/update-with-output-clause-triggers-and-sqlmoreresults.aspx
Entity Framework performs something similar to gbn's answer:
DECLARE #generated_keys table([Id] uniqueidentifier)
INSERT INTO Customers(FirstName)
OUTPUT inserted.CustomerID INTO #generated_keys
VALUES('bob');
SELECT t.[CustomerID]
FROM #generated_keys AS g
JOIN dbo.Customers AS t
ON g.Id = t.CustomerID
WHERE ##ROWCOUNT > 0
The output results are stored in a temporary table variable, and then selected back to the client. Have to be aware of the gotcha:
inserts can generate more than one row, so the variable can hold more than one row, so you can be returned more than one ID
I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).
But that's what EF does.
SQL Server 2008 or newer only. If it's 2005 then you're out of luck.
There are many ways to exit after insert
When you insert data into a table, you can use the OUTPUT clause to
return a copy of the data that’s been inserted into the table. The
OUTPUT clause takes two basic forms: OUTPUT and OUTPUT INTO. Use the
OUTPUT form if you want to return the data to the calling application.
Use the OUTPUT INTO form if you want to return the data to a table or
a table variable.
DECLARE #MyTableVar TABLE (id INT,NAME NVARCHAR(50));
INSERT INTO tableName
(
NAME,....
)OUTPUT INSERTED.id,INSERTED.Name INTO #MyTableVar
VALUES
(
'test',...
)
IDENT_CURRENT: It returns the last identity created for a particular table or view in any session.
SELECT IDENT_CURRENT('tableName') AS [IDENT_CURRENT]
SCOPE_IDENTITY: It returns the last identity from a same session and the same scope. A scope is a stored procedure/trigger etc.
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
##IDENTITY: It returns the last identity from the same session.
SELECT ##IDENTITY AS [##IDENTITY];
##IDENTITY Is a system function that returns the last-inserted identity value.
There are multiple ways to get the last inserted ID after insert command.
##IDENTITY : It returns the last Identity value generated on a Connection in current session, regardless of Table and the scope of statement that produced the value
SCOPE_IDENTITY(): It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table.
IDENT_CURRENT(‘TABLENAME’) : It returns the last identity value generated on the specified table regardless of Any connection, session or scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.
Now it seems more difficult to decide which one will be exact match for my requirement.
I mostly prefer SCOPE_IDENTITY().
If you use select SCOPE_IDENTITY() along with TableName in insert statement, you will get the exact result as per your expectation.
Source : CodoBee
The best and most sure solution is using SCOPE_IDENTITY().
Just you have to get the scope identity after every insert and save it in a variable because you can call two insert in the same scope.
ident_current and ##identity may be they work but they are not safe scope. You can have issues in a big application
declare #duplicataId int
select #duplicataId = (SELECT SCOPE_IDENTITY())
More detail is here Microsoft docs
You can use scope_identity() to select the ID of the row you just inserted into a variable then just select whatever columns you want from that table where the id = the identity you got from scope_identity()
See here for the MSDN info http://msdn.microsoft.com/en-us/library/ms190315.aspx
Recommend to use SCOPE_IDENTITY() to get the new ID value, But NOT use "OUTPUT Inserted.ID"
If the insert statement throw exception, I except it throw it directly. But "OUTPUT Inserted.ID" will return 0, which maybe not as expected.
This is how I use OUTPUT INSERTED, when inserting to a table that uses ID as identity column in SQL Server:
'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)
You can append a select statement to your insert statement.
Integer myInt =
Insert into table1 (FName) values('Fred'); Select Scope_Identity();
This will return a value of the identity when executed scaler.
* Parameter order in the connection string is sometimes important. * The Provider parameter's location can break the recordset cursor after adding a row. We saw this behavior with the SQLOLEDB provider.
After a row is added, the row fields are not available, UNLESS the Provider is specified as the first parameter in the connection string. When the provider is anywhere in the connection string except as the first parameter, the newly inserted row fields are not available. When we moved the the Provider to the first parameter, the row fields magically appeared.
After doing an insert into a table with an identity column, you can reference ##IDENTITY to get the value:
http://msdn.microsoft.com/en-us/library/aa933167%28v=sql.80%29.aspx

Resources