I have a table that holds organization data. I also have a new table that is going to hold info about shipping containers.
As an initial test I want to populate the new Shipping_Containers table by giving one container to each organization.
So I thought about getting the organization ids and looping through them and doing an insert into Shipping_Containers for each organization id, something like this:
select * into #orgs from Organization_1
while (select id from #orgs ) IS NOT NULL
begin
insert into Shipping_Containers (name, org)
values('test_name', id)
end
I know there is probably a lot wrong with that but firstly it is giving this error:
Msg 207, Level 16, State 1, Line 4
Invalid column name 'id'.
I'm using SQL Server 2008 R2 and I'm new to T-SQL so any guidance here would be appreciated, thanks.
Try
INSERT INTO Shipping_Containers (name, org)
SELECT 'test_name', id
FROM Organization_1
Related
I have a requirement where I need to insert new entries found in a record into its Master Table and Map the ID of the identifier to the main table
For Instance consider the below example,
-- Insert into Category Master if not exists
INSERT INTO tblCategoryMaster (Category,
CreatedBy,
CreatedDate,
UpdatedBy,
UpdatedDate)
SELECT DISTINCT
(category),
SERVERPROPERTY('MACHINENAME'),
GETDATE(),
SERVERPROPERTY('MACHINENAME'),
GETDATE()
FROM tblTempDataStaging stg
WHERE category IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM tblCategoryMaster ctg WHERE ctg.Category = stg.category);
After executing the select query we get list of distinct entries and every time a new entry is entered in the staging table, the entries are populated in the Master Table accordingly.
Server is not allowing me to insert, its giving me an error saying
Msg 257, Level 16, State 3, Line 39
Implicit conversion from data type sql_variant to nvarchar(max) is not allowed. Use the CONVERT function to run this query.
The data type of the staging table is NVARCHAR(MAX) for the relevant fields except datetime for the date fields
Tried using CONVERT method but I'm unsure on how do we use it with DISTINCT in the picture
Can you suggest how do I resolve this issue?
The error is telling you the problem: SERVERPROPERTY('MACHINENAME') returns the datatype sql_variant:
SELECT system_type_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT SERVERPROPERTY(''MACHINENAME'') AS MachineName',NULL,NULL);
The underlying data type is a nvarchar (thought it certainly won't be 2GB of storage for the name of a machine!) as can be seen here:
SELECT SQL_VARIANT_PROPERTY(SERVERPROPERTY('MACHINENAME'),'Basetype')
You need to explicitly convert the value. For example:
CONVERT(nvarchar(256),SERVERPROPERTY('MACHINENAME'))
I do suggest you change the data type of your column CreatedBy, and I assume UpdatedBy, from nvarchar(MAX) to something like an nvarchar(256); you don't need 2GB of characters (about 1 Billion) to store that information.
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
I have three tables
Node
- NodeID
Role
- RoleID
NodeRoles
- NodeID
- RoleID
For every record in NodeID I'd like to create a record in NodeRoles against every record in table Role.
this was my attempt at solving the above.
INSERT INTO NodeRoles (NodeID, RoleID)
VALUES ( SELECT NodeID from Node, SELECT RoleID from Role )
This seems like a simple approach and the idea feels right, but the error that comes back is that we're reporting multiple values into a singluar column. Which reviewing that makes sense as that's exactly what is happening.
In application code I would simply set up two foreach loops, but I'm not sure how to get the same thing in SQL. Thank you!
Try this:
INSERT INTO NodeRoles (NodeID, RoleID)
( SELECT NodeID,RoleID from Node,Role )
In SQL Server, i am inserting multiple records into table using batch update. How do i get back the ID's (unique primary key) which is being created after batch update?
If I insert one record, I can get the last inserted using IDENT(tableName). I am not sure how to get if I do batch update. Please help.
For example, I have student table, with ROLE NO and NAME. ROLE NO is auto incremented by 1, as soon I insert the names into DB using java program. I will add 3 rows at a time using batch update from my java code. In DB, it gets added with ROLE NO 2, 3 and 4. How do I get these newly generated ID in my java program, please help
I tried getting ids using getgeneratedkeys method after I do executebatch. I get exception. Is batch update + get generated keys supported.?
In SQL Server when you do an insert there is an extra option your query; OUTPUT. This will let you capture back the data you inserted into the table - including your id's. You have to insert them into a temporary table; so something like this (with your table/ column names will get you there.
declare #MyNewRoles Table (Name, RoleNo)
insert into tblMyTable
(Name)
Select
Name
Output
inserted.Name, Inserted.RoleNo
into #MyNewRoles
From tblMyTableOfNames
select * from #MyNewRoles
If you don't mind adding a field to your table, you could generate a unique ID for each batch transaction (for example, a random UUID), and store that in the table as well. Then, to find the IDs associated with a given transaction you would just need something like
select my_id from my_table where batch_id = ?
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)