How to create a stored procedure to copy data from a query to a temporary table? - sql

I have need of inserting data to a temporary table from an existing table/query. The following produces the error detailed below.
CREATE TABLE SPTemporary
AS
BEGIN
SELECT * into #temppT
FROM SampleTable
END
Throws this error:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'begin'.

Correct your syntax, use procedure instead of table :
create procedure SPTemporay
as
begin
select * into #temppT
from SampleTable
end
However, if you want only copy of data then only subquery is enough :
select st.* into #temppT
from SampleTable st

One method is:
select st.*
into SPTemporay
from SampleTable st
One select can only put data in one table. It is unclear which one you really want SPTemporary or #temppT. You can repeat the select if you really need the same data in two tables.
EDIT:
If you want a stored procedure, you could do:
create procedure SPTemporay
as begin
select *
into #temppT
from SampleTable
end;
This is rather non-sensical, because the temporary table is discarded when the stored procedure returns.

I think the syntax is wrong, it should be like that:
create table SPTemporay
as
select * from SampleTable
I hope this helps.

Related

Postgresql Procedure select into temp table

Being a recent convert from SQL Server, I am getting to know Postgresql a bit.
I really hate having to write nested selevt statements in SQL since I find that the readability and maintainability of the code suffers when I do.
Usually I would create a stored procedure in SQL Server where I would select something into a temporary table, that I can then use in another select statement.
CREATE OR ALTER PROCEDURE Procname
AS
BEGIN
SELECT
Somewhere.Col_1,
Somewhere.Col_2
INTO
#Temptable
FROM
Somewhere Somewhere
SELECT
Temptable.Col_1,
Somewhere_Else.Col3
FROM
#Temptable Temptable
INNER JOIN
Somewhere_Else.Col_2 = Temptable.Col_2
END
When I execute this procedure I would get returned the final select query
How would I replicate this procedure in Postgresql?
I know that you can select into a temporary table, but I cannot seem to figure out how to use this table in the next select statement within the same procedure
Create a set returning function, there is no need for a temp table at all.
CREATE function Procname()
returns table(col_1 ???, col2 ???) --<< change data types here
AS
$$
SELECT
Temptable.Col_1,
Somewhere_Else.Col3
FROM Somewhere Temptable
INNER JOIN Somewhere_Else ON Somewhere_Else.Col_2 = Temptable.Col_2;
$$
language sql
stable;
But for such a simple statement, I would rather create a view.

Calling Stored procedure with cross apply from another stored procedure gives error SQL server

I have been trying to call stored procedure from another stored procedure. Now issue is that under lying nested stored procedure contains CROSS APPLY with temp table and it runs fine when i execute it directly.
But when i try to call this SP from other SP, it gives error that one of the column is invalid. "Invalid column name 'levels'" in this case.
Plus, when i execute this SP from calling SP SQL window with passing parameters, it runs fine and whole main procedure starts running smoothly.
I am not able to get why this issue happens. Below is kind of implementation for reference.
1.) Main SP
CREATE STORED PROCEDURE ....
INSERT INTO #TempTable
EXEC [Child_SP] #Param1 = 1, #Param2 = 1
...
Gives error.
2.) Once i execute below given as single statement once from main PS. It starts working fine.
EXEC [Child_SP] #Param1 = 1, #Param2 = 1
3.) Child SP has CROSS APLLY with one of the temp table. something like below.
SELECT ID, '1,2,3,4,5' AS levels
INTO #Temp1
FROM ABC
SELECT ID
FROM #Temp1 x0
CROSS APPLY (SELECT * FROM dbo.iter_charlist_to_table(x0.levels, ',') AS x) x1
WHERE x1.listPos > 1
"iter_charlist_to_table" is table value function which get values as table from comma seperated list.
Is it related to SQL Thread anyhow or whats the issue? Thanks.
I recommend to use this code to drop your tmp table on the beginning of the SP because your insert INTO will ALWAYS tried to create the table doesn't matter if already exists.
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL DROP TABLE #Temp1
If you share more code will be more helpful to understand.
And just in case don't forget to put the alias on the table maybe this correction sometimes is not needed but is a good practice for avoid problems on querying the data on joined tables
SELECT x0.ID
FROM #Temp1 x0
CROSS APPLY (SELECT fnAlias.* FROM dbo.iter_charlist_to_table(x0.levels, ',') fnAlias) x1
WHERE x1.listPos > 1

SAP HANA: Loading tables from with statements in stored procedures

Is it possible to load a table from a with statement via a stored procedure in HANA? Nothing i try seems to work, and the only thing that does work when creating a procedure is just displaying the data from the with statement via a select. Below I show three examples I have tried for accessing with statement data. Currently on HANA revision 84. Please note the table create is just for purposes of the test example.
CREATE PROCEDURE test_proc
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
AS
BEGIN
create table t1 (cal_day date);
with w1 as (
select current_date cal_day from dummy
)
--works just fine but isn't loading the data into anything
select * from w1;
--get indentifier must be declared error
select cal_day into t1 from w1;
--get incorrect syntax error
insert into t1
select cay_day from w1;
END
When you want to execute DDL statements in a SQLScript procedure you'll need to use dynamic SQL for that (EXEC).

Odd Stored Procedure error - syntax?

I am trying to create a simple stored procedure in SQL Server 2005, and am puzzled by a syntax error I am getting.
Both tables have identical structure. tbl_Users_non_61 is empty and ready to receive the data.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Make_WEEKLY_SUMMARY
AS
BEGIN
SET NOCOUNT ON;
Select (tbl_Users.UserID
, tbl_Users.RegistrationType
, tbl_Users.Datecompleted)
INTO tbl_Users_non_61
FROM
SELECT tbl_Users.UserID
, tbl_Users.RegistrationType
, tbl_Users.Datecompleted
FROM tbl_Users;
END
GO
Resulting error:
Msg 102, Level 15, State 1, Procedure Make_WEEKLY_SUMMARY, Line 5
Incorrect syntax near ','.**
Since you just want to insert records into one table from another, there is a cleaner syntax:
INSERT INTO tbl_Users_non_61(UserId, RegistrationType, DateCompleted)
SELECT u.UserID, u.RegistrationType, u.Datecompleted
FROM tbl_Users AS u
To answer your question though, you do not need the ( ) around your first select, but you DO need them around your sub select, then you need to alias the sub-query you are referencing with the FROM:
Select t.UserID, t.RegistrationType, t.Datecompleted
INTO tbl_Users_non_61
FROM
(
SELECT u.UserID, u.RegistrationType, u.Datecompleted
FROM tbl_Users AS u
) as t;
Try this on:
SELECT
tbl_Users.UserID
, tbl_Users.RegistrationType
, tbl_Users.Datecompleted
INTO tbl_Users_non_61
FROM tbl_Users;
When you SELECT ... INTO, if the columns come from one table only, there's no need to SELECT those same columns again. Even if you had to take data from multiple columns, you still wouldn't need to reselect them, and perform a join instead.

Stored Procedure consist Add column, Update data for that column, and Select all data from that table

I've written a stored procedure as following:
CREATE PROC spSoNguoiThan
#SNT int
AS
begin
IF not exists (select column_name from INFORMATION_SCHEMA.columns where
table_name = 'NhanVien' and column_name = 'SoNguoiThan')
ALTER TABLE NhanVien ADD SoNguoiThan int
else
begin
UPDATE NhanVien
SET NhanVien.SoNguoiThan = (SELECT Count(MaNguoiThan)FROM NguoiThan
WHERE MaNV=NhanVien.MaNV
GROUP BY NhanVien.MaNV)
end
SELECT *
FROM NhanVien
WHERE SoNguoiThan>#SNT
end
GO
Then I get the error :
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 12
Invalid column name 'SoNguoiThan'.
Server: Msg 207, Level 16, State 1, Procedure spSoNguoiThan, Line 15
Invalid column name 'SoNguoiThan'.
Who can help me?
Thanks!
When the stored proc is parsed during CREATE the column does not exist so you get an error.
Running the internal code line by line works because they are separate. The 2nd batch (UPDATE) runs because the column exists.
The only way around this would be to use dynamic SQL for the update and select so it's not parsed until EXECUTE time (not CREATE time like now).
However, this is something I really would not do: DDL and DML in the same bit of code
I ran into this same issue and found that in addition to using dynamic sql I could solve it by cross joining to a temp table that had only one row. That caused the script compiler to not try to resolve the renamed column at compile time. Below is an example of what I did to solve the issue without using dynamic SQL
select '1' as SomeText into #dummytable
update q set q.ValueTXT = convert(varchar(255), q.ValueTXTTMP) from [dbo].[SomeImportantTable] q cross join #dummytable p