SQL Server Insert Into Temp table from a table variable - sql

I need to insert data in my table variable to a temp table but it gives me the following error.
Msg 208, Level 16, State 0, Procedure sp_CreateScenario_q2, Line 70
Invalid object name '#tmpp1'.
Here is the code
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1
INSERT INTO #tmpp1
SELECT
[PlanningHierarchyId]
,[ProductReferenceId]
,[PlanningYear]
,[PlanningSeason]
,[UpdatedBy]
FROM
#paramTable
Is there any way to do this?

Error 'Invalid object name '#tmpp1' occurs because you delete temp table and then try to insert in it.
Try to use:
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1
SELECT
[PlanningHierarchyId]
,[ProductReferenceId]
,[PlanningYear]
,[PlanningSeason]
,[UpdatedBy]
INTO #tmpp1
FROM #paramTable

you are dropping table. Either create one with CREATE or use select * into instead of insert into
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1
SELECT
[PlanningHierarchyId]
,[ProductReferenceId]
,[PlanningYear]
,[PlanningSeason]
,[UpdatedBy] into #tmpp1
FROM #paramTable

Insert into is used when table already exists use SELECT into from . When you're trying to insert in temp table, temp table doesn't exists.
Refer : INSERT INTO vs SELECT INTO
IF OBJECT_ID('tempdb..#tmpp1') IS NOT NULL
DROP TABLE #tmpp1;
SELECT
[PlanningHierarchyId]
,[ProductReferenceId]
,[PlanningYear]
,[PlanningSeason]
,[UpdatedBy]
INTO #tmpp1
FROM #paramTable

Related

Why is this temporary table throwing an error about the number of column supplied?

I'm trying to run this specific code for a temp table, but somehow I get this error
Column name or number of supplied values does not match table definition
What's wrong?
DROP TABLE IF EXISTS #GamesDistribution
CREATE TABLE #GamesDistribution
(
Platform nvarchar(255),
Name nvarchar(255),
NA_Sales numeric,
EU_Sales numeric,
JP_Sales numeric
)
INSERT INTO #GamesDistribution
SELECT
properties.Platform,
properties.Name,
revenue.NA_Sales,
revenue.EU_Sales,
revenue.JP_Sales
FROM
games_properties AS Properties
JOIN
games_revenue AS Revenue ON properties.Game_ID = Revenue.Game_ID
--GROUP BY properties.platform
--ORDER BY Total_Games DESC, Total_NA_Sales DESC, Total_EU_Sales DESC, Total_JP_Sales DESC;
The problem here is that prior to you running your batch the table already exists. As such when the batch is parsed, by the compiler, the compilation fails; because the number of columns doesn't match that of the table already exists.
This can be replicated with the following:
CREATE TABLE #t (I int);
INSERT INTO #t (I)
VALUES(1);
GO
DROP TABLE IF EXISTS #t;
CREATE TABLE #t (I int, D date);
INSERT INTO #t
VALUES(2,GETDATE());
GO
SELECT *
FROM #t;
GO
DROP TABLE #t
db<>fiddle
This returns the error:
Msg 213, Level 16, State 1, Line 10
Column name or number of supplied values does not match table definition.
And the dataset:
I
1
This is because the 2nd batch, with the DROP TABLE IF EXISTS never ran; the compilation failed.
The "simple" solution here would be to put your DROP IF EXISTS in a separate batch, and also specify your columns:
DROP TABLE IF EXISTS #GamesDistribution;
GO
CREATE TABLE #GamesDistribution (Platform nvarchar(255),
Name nvarchar(255),
NA_Sales numeric, --Where is your precision and scale?
EU_Sales numeric, --Where is your precision and scale?
JP_Sales numeric); --Where is your precision and scale?
INSERT INTO #GamesDistribution (Platform,Name, NA_Sales,EU_Sales,JP_Sales)
SELECT properties.Platform,
properties.Name,
revenue.NA_Sales,
revenue.EU_Sales,
revenue.JP_Sales
FROM dbo.games_properties AS Properties
JOIN dbo.games_revenue AS Revenue ON properties.Game_ID = Revenue.Game_ID;
You can actually do this way
DROP TABLE IF EXISTS #GamesDistribution
SELECT properties.Platform,
properties.Name,
revenue.NA_Sales,
revenue.EU_Sales,
revenue.JP_Sales
INTO #GamesDistribution
FROM games_properties AS Properties
JOIN games_revenue AS Revenue
ON properties.Game_ID = Revenue.Game_ID
and then you can check the columns' data types of the temp table:
EXEC tempdb..sp_help '#GamesDistribution'
SELECT *
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID('tempdb..#GamesDistribution');
Note: It's always better to ensure the columns' data types. Your query might list different columns' data types.
Add GO statement under drop table as below.
DROP TABLE IF EXISTS #GamesDistribution
GO
CREATE TABLE #GamesDistribution
(
.
.
.

Copy data from one table to another while at the same time insert a guid SQL

I have over 13,000 records in an existing table called "AnyName"
I need to move the records to a new table Called "DomainObject2" New, this table will have a Guid primary column named "Oid"
I get the following error when i execute the below code.
Cannot insert the value NULL into column 'Oid', table 'NewDatabase.dbo.DomainObject2'; column does not allow nulls. INSERT fails.
USE NewDatabase
INSERT INTO NewDatabase.dbo.DomainObject2
([Ano]
,[C1]
,[C2]
,[C3]
,[C4]
,[C5]
,[CF]
,[CF2]
,[CF3]
,[CF4]
,[CF5])
SELECT
[ano]
,[c1]
,[c2]
,[c3]
,[c4]
,[c5]
,[cf]
,[cf2]
,[cf3]
,[cf4]
,[cf5]
FROM AnyName.dbo.[Old_Table];
GO```
Thanks in advance!!!
Try this:
INSERT INTO NewDatabase.dbo.DomainObject2
([Oid]
,[Ano]
,[C1]
,[C2]
,[C3]
,[C4]
,[C5]
,[CF]
,[CF2]
,[CF3]
,[CF4]
,[CF5])
SELECT NewID()
,[ano]
,[c1]
,[c2]
,[c3]
,[c4]
,[c5]
,[cf]
,[cf2]
,[cf3]
,[cf4]
,[cf5]
FROM AnyName.dbo.[Old_Table];

Create a procedure to insert multiple values into a table, using a single variable

Goal: To create a procedure to insert multiple values into a table, using a single variable.
Challenge: Instead of making multiple hits in the same table, I have created a single variable (#SQL) and stored multiple columns (fm_id and shdl_id ) results in it but I am unable to use this single variable in the insert statement.
Code:
create proc abc
(
#org_id numeric(10,0),
#shdl_id numeric(10,0),
#usr_id numeric(10,0),
#tst_id numeric(10,0)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #SQL NUMERIC(10);
SET #SQL= (SELECT fm_id,#shdl_id FROM [dbo].[students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id)
INSERT INTO [USER]
SELECT org_id,#usr_id,TST_ID,login_name,#SQL FROM [students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id
END
GO
Error :
Msg 213, Level 16, State 1, Procedure abc, Line 14 [Batch Start Line
94] Column name or number of supplied values does not match table
definition.
First you need to make your SELECT return only one value into the variable. There's no point selecting #shdl_id because you already know it?
DECLARE #pFMID NUMERIC(10);
SELECT #pFMID = MAX(fm_id) FROM [dbo].[students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id);
Then because you're not inserting a value into every column in the user table you need to explicitly state which columns to fill. Replace x1..x5 below with real column names (in the order the SELECT has them)
INSERT INTO [USER](x1,x2,x3,x4,x5)
-- ^^^^^^^^^^^^^^^
-- REPLACE THESE WITH REAL NAME
SELECT org_id,#usr_id,TST_ID,login_name,#pFMID FROM [students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id
END
GO
And as Uueerdo pointed out, this first query is a bit of a waste of time, we can write this:
create proc abc
(
...
)
AS
BEGIN
INSERT INTO [USER](x1,x2,x3,x4,x5)
SELECT org_id,#usr_id,TST_ID,login_name,fm_id FROM [students] WHERE ORG_ID=#org_id AND shdl_id=#shdl_id AND TST_ID=#tst_id
-- ^^^^^
-- look!
You can only get away with leaving the column list off an INSERT if you're inserting the same number of columns the table has:
CREATE TABLE x(col1 INT, col2 INT);
INSERT INTO x VALUES (1,2) -- works
INSERT INTO x VALUES (1) -- fails: which column should have the 1?
INSERT INTO x(col1) VALUES (1) -- works: col1 shall have the 1

Using OUTPUT INTO with from_table_name in an INSERT statement [duplicate]

This question already has answers here:
Is it possible to for SQL Output clause to return a column not being inserted?
(2 answers)
Closed 2 years ago.
Microsoft's OUTPUT Clause documentation says that you are allowed to use from_table_name in the OUTPUT clause's column name.
There are two examples of this:
Using OUTPUT INTO with from_table_name in an UPDATE statement
Using OUTPUT INTO with from_table_name in a DELETE statement
Is it possible to also use it in an INSERT statement?
INSERT INTO T ( [Name] )
OUTPUT S.Code, inserted.Id INTO #TMP -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
Failing example using table variables
-- A table to insert into.
DECLARE #Item TABLE (
[Id] [int] IDENTITY(1,1),
[Name] varchar(100)
);
-- A table variable to store inserted Ids and related Codes
DECLARE #T TABLE (
Code varchar(10),
ItemId int
);
-- Insert some new items
WITH S ([Name], Code) AS (
SELECT 'First', 'foo'
UNION ALL SELECT 'Second', 'bar'
-- Etc.
)
INSERT INTO #Item ( [Name] )
OUTPUT S.Code, inserted.Id INTO #T -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
No, because an INSERT doesn't have a FROM; it has a set of values that are prepared either by the VALUES keyword, or from a query (and even though that query has a FROM, you should conceive that it's already been run and turned into a block of values by the time the insert is done; there is no s.code any more)
If you want to output something from the table that drove the insert you'll need to use a merge statement that never matches any records (so it's only inserting) instead, or perhaps insert all your data into #tmp and then insert from #tmp into the real table - #tmp will thus still be the record of rows that were inserted, it's just that it was created to drive the insert rather than as a consequence of it (caveats that it wouldn't contain calculated columns)

Hive - How to insert in a hive table an array of struct

So I learnt from here how to insert values into an array column:
INSERT INTO table
SELECT ARRAY("line1", "line2", "line3") as myArray
FROM source1;
And from here how to insert values into an struct column:
INSERT INTO table
SELECT NAMED_STRUCT('houseno','123','streetname','GoldStreet', 'town','London', 'postcode','W1a9JF') AS address
FROM source2;
Now I was trying to insert in the same way values in an array of structs. Which has got the following schema:
additionalattribute:array<struct<attribute_value:string,key:string,value:string>
I tried to extrapolate like this:
INSERT INTO table
ARRAY(NAMED_STRUCT('attribute_value','null','key','null','value','null')) as additionalattribute
FROM source2;
But it is not working. Does anyone know how to approach this issue?
you are missing the select statement after the table name. Demo
create table temp4
(
additionalattribute array<struct<attribute_value:string,key:string,value:string>>
);
INSERT INTO temp4 select
ARRAY(NAMED_STRUCT('attribute_value','null','key','null','value','null')) as additionalattribute
FROM (select '1' ) t;