How to create a new table with the select query results - sql

I want to convert the obtained query (below exposed, see:code) into a new table so I can compute and process the data more easily..
I know this question sounds stupid, but when I use:
SELECT X.*
INTO NewTable
FROM
(
SELECT .... complex query ....
FROM ...
...
) AS X
It sends me an error message, how am I supposed to enter my query into this code above mentioned..
Error:
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'select'.
Msg 156, Level 15, State 1, Line 54
Incorrect syntax near the keyword 'from'.
Code:
SELECT *
INTO Price_to_book_valid
FROM
(
select *
from pricetobook
declare #sql nvarchar(max);
declare #fields nvarchar(max);
set #fields=stuff((select ',['+column0+']'
from dll_ptbv
where column0 not in ('Code','Mnemonic')
group by column0
order by case when column0='Name' then 0 else 3 end
,column0
for xml path('')
,type
).value('.','nvarchar(max)')
,1 ,1 ,'');
set#sql='select'+#fields
+ 'from (select column0
,column1
,sum(rn1*rn2) over(order by rn2) as rn
from (select column0
,column1
,case when column0=''Name'' then 1 else 0 end as rn1
,row_number() over(order by (select null)) as rn2
from dll_ptbv
) as a
) as a
pivot (max(column1) for column0 in ('+#fields+')) as p
order by [Name]';
execute sp_executesql #sql;

You coudl use a select INTO before column Name
SELECT * INTO NewTable
FROM
(
SELECT .... complex query ....
FROM ...
...
) p <<<<<<<< remove as
( you should remove as in as a) fist you should assign a table name and eventulally after you can use an alais

-- 14. SELECT INTO new table from dynamic stored procedure execution.
-- Dynamic stored procedure to temporary table
USE tempdb;
GO
-- SQL create dynamic stored procedure
CREATE PROCEDURE DynamicSprocToTempTable
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = 'SELECT top (5) * from AdventureWorks.Purchasing.PurchaseOrderHeader
ORDER BY NEWID()'
-- Dynamic SQL
EXEC Sp_executesql #SQL
END
GO
-- Test stored procedure
EXEC tempdb.dbo.DynamicSprocToTempTable
GO
-- Select into temporary table from OPENQUERY
-- SQL select into temp table
SELECT * INTO #poh
FROM Openquery(SERVERALPHA,'exec tempdb.dbo.DynamicSprocToTempTable')
GO
SELECT PurchaseOrderID, VendorID, OrderDate
FROM #poh
/* Results
PurchaseOrderID VendorID OrderDate
2662 50 2004-05-19 00:00:00.000
2454 44 2004-05-01 00:00:00.000
2547 96 2004-05-10 00:00:00.000
901 54 2003-10-13 00:00:00.000
2675 74 2004-05-22 00:00:00.000
*/
GO

Related

How to get Output parameter from a column in table for a stored procedure

I've stored procedure like this:
create procedure sp_testsp
(
#vc_order_by varchar(100),
#int_start_index INT,
#int_grid_size INT,
#count bigint output
)
as
begin
select * from
(select ROW_NUMBER() over
(order by
case #vc_order_by = '' then tab1.int_id end desc) AS row,
*,
COUNT(tab1.int_id) OVER() as totalRowCount
from
(select * from tbl_test) tab1) tab2
where row BETWEEN CONVERT(VARCHAR, #int_start_index) and CONVERT(VARCHAR,(#int_start_index-1) + #int_grid_size);
set #count = 0;
end
We can execute the above stored procedure by:
DECLARE #size bigint;
EXEC sp_testsp '', 1,5, #size output;
SELECT #size;
The written sp provides data based on pagination and we can retrieve 100 or any number of records by passing a number in #int_grid_size .
The table output looks like following:
row int_id vc_name totalRowCount
1 5 a 107
2 6 ab 107
3 7 abc 107
4 8 abcd 107
5 10 abcc 107
The last column gives the total records count of the table or total record if we use where condition.
I want to OUTPUT any one column value of the totalRowCount in '#count' in the stored procedure.
I cannot use ##ROWCOUNT as it only sends the count of records the sp is outputting i.e in this case 5 but actual records are 107.
Just wondering if there is any way. Any help is apperciated. Thanks.
Edit:
I tried something like this, and it works:
create procedure sp_testsp
#param1 nvarchar(800),
#count bigint output
as
begin
select * from tbl_test tt where tt.col1 = #param1;
set #count = select Count(*) from tbl_test tt where tt.col1 = #param1;
end
The issue with this is I've to call the query once and then call the query again for #count. This is working but taking lot of time for big queries.
You can do that by temp table
select * into #temp from
(select ROW_NUMBER() over
(order by
case #vc_order_by = '' then tab1.int_id end desc) AS row,
*,
COUNT(tab1.int_id) OVER() as totalRowCount
from
(select * from tbl_test) tab1) tab2
where row BETWEEN CONVERT(VARCHAR, #int_start_index) and CONVERT(VARCHAR,(#int_start_index-1) + #int_grid_size);
select top 1 #count=totalRowCount from #temp
select * from #temp --you can exclude totalRowCount

How to create stored procedure with view?

I tried to execute this code and it worked o.k without the the stored procedure and with it, it made an error.
The error is:
Msg 102, Level 15, State 1, Procedure UV_MTBF, Line 251
Incorrect syntax near 'Event_'.
Is the stored procedure have a limitation in length?
can someone help me with my code?
edit*
my problem is with ' + QUOTENAME(#category,N'''') + N'
i want to add an integer from a variable that i received in the stored procedure. how can i do it?
enter code here:
CREATE PROCEDURE dbo.MTBFCalculation #Category int, #Action bit, #relateToParent bit
as
IF EXISTS (SELECT 1 FROM sys.objects WHERE [name] = '[dbo].[UV_MTBF]')
DROP VIEW [dbo].[UV_MTBF];
DECLARE #Event nvarchar(MAX) = N'
CREATE VIEW [dbo].[UV_MTBF]
as
with failureReportTable as (SELECT [ID] as failure_id
,[Login_ID]
,[Event_ID]
,[StartDate]
,[EndDate]
,DATEDIFF(Hour,[StartDate],[EndDate]) as eventDurationMin
,[IsRelevantForBI]
,[IsParallelReport]
,[ParentReportID]
,[IsPausedEvent]
,Case
When ParentReportID>0 Then 1 --Chiled
When IsParallelReport=1 Then 2 --Parent
Else 3 --not Parallel
End as ParallelStatus
FROM [TDM_Analysis].[dbo].[FailureReports]),
fullFailure as (select *, ROW_NUMBER() OVER (ORDER BY [StartDate] ) AS IDrow
from failureReportTable join [TDM_Analysis].[dbo].[UV_filteredLogins] as viewLogins on failureReportTable.Login_ID=viewLogins.ID
WHERE event_id IN (SELECT ID FROM [TDM_Analysis].[dbo].[Events] where EventCategory_ID=' + QUOTENAME(#category,N'''') + N')
and (ParallelStatus=3 or ParallelStatus=(case when ' + QUOTENAME(#relateToParent,N'''') + N'=1 then 2 else 1 end))),
--------------create first failure table------------------
failure_Event_1 as (select f1.failure_id as Event_1_Failure_ID
,f1.[Login_ID] as Event_1_Login_ID
,f1.[Event_ID] as Event_1_Event_ID
,f1.[StartDate] as Event_1_StartDate
,f1.[EndDate] as Event_1_EndDate
,f1.eventDurationMin as Event_1_eventDurationMin
--,f1.[IsRelevantForBI] as Event_1_IsRelevantForBI
--,f1.[IsParallelReport] as Event_1_IsParallelReport
-- ,f1.[ParentReportID] as Event_1_ParentReportID
-- ,f1.[IsPausedEvent] as Event_1_IsPausedEvent
,f1.[Test_Name] as Event_1_TestName
,f1.Phase_Name as Event_1_PhaseName
,f1.PressName as Event_1_PressName
,f1.PressType as Event_1_PressType
--,f1.[Operator] as Event_1_Operator
,f1.[LoginDate] as Event_1_LoginDate
,f1.[LogoutDate] as Event_1_LogoutDate
,f1.TimeDiff as Event_1_LoginDuration
,f1.IDrow+1 as row1
from fullFailure as f1),
--------------create second failure table------------------
failure_Event_2 as (select f1.failure_id as Event_2_Failure_ID
,f1.[Login_ID] as Event_2_Login_ID
,f1.[Event_ID] as Event_2_Event_ID
,f1.[StartDate] as Event_2_StartDate
,f1.[EndDate] as Event_2_EndDate
,f1.eventDurationMin as Event_2_eventDurationMin
-- ,f1.[IsRelevantForBI] as Event_2_IsRelevantForBI
-- ,f1.[IsParallelReport] as Event_2_IsParallelReport
-- ,f1.[ParentReportID] as Event_2_ParentReportID
-- ,f1.[IsPausedEvent] as Event_2_IsPausedEvent
,f1.[Test_Name] as Event_2_TestName
,f1.Phase_Name as Event_2_PhaseName
,f1.PressName as Event_2_PressName
,f1.PressType as Event_2_PressType
-- ,f1.[Operator] as Event_2_Operator
,f1.[LoginDate] as Event_2_LoginDate
,f1.[LogoutDate] as Event_2_LogoutDate
,f1.TimeDiff as Event_2_LoginDuration
,f1.IDrow as row2
from fullFailure as f1),
------------- join two failure tabels and calculating MTTR-mean time to repair (duration of failue), MTTF-mean time to failue( end of one until start of a new one), MTBF-mean time between failue (from start of a failure to start of a new one)--------------------
joinFailures as (select *, Event_1_eventDurationMin as MTTR
,CASE
When isnull(f2.row2,0)=0 then DATEDIFF(HOUR,f1.Event_1_EndDate,f1.Event_1_LogoutDate)
WHEN f1.Event_1_Login_ID=f2.Event_2_Login_ID THEN DATEDIFF(HOUR,f1.Event_1_EndDate,f2.Event_2_StartDate)
When (select TOP 1 sum(timediff)
from [TDM_Analysis].[dbo].[UV_filteredLogins]
where logindate>f1.Event_1_LogoutDate and logindate<f2.Event_2_LoginDate) is null then DATEDIFF(HOUR,f1.Event_1_EndDate,f1.Event_1_LogoutDate)+DATEDIFF(HOUR,f2.Event_2_LoginDate, f2.Event_2_StartDate)
ELSE
(select TOP 1 sum(timediff)+DATEDIFF(HOUR,f1.Event_1_EndDate,f1.Event_1_LogoutDate)+DATEDIFF(HOUR,f2.Event_2_LoginDate, f2.Event_2_StartDate)
from [TDM_Analysis].[dbo].[UV_filteredLogins]
where logindate>f1.Event_1_LogoutDate and logindate<f2.Event_2_LoginDate)
END AS MTTF
from failure_Event_1 as f1 left join failure_Event_2 as f2 on f1.row1=f2.row2),
positiveJoinFailure as (select * from joinFailures where MTTF>=0)
---- select calculation table order by ascending time----------
select * --Event_1_Failure_ID,Event_2_Failure_ID,MTTR,MTTF, MTTR+MTTF as MTFB
from positiveJoinFailure
--order by row1
';
--------------------------------------------------------Action------------------------------------------------------------------------------
if #Action=1
begin
EXEC sp_executesql #Event;
end
for this part of your query
where EventCategory_ID=' + QUOTENAME(#category,N'''') + N')
2 option here, you convert the value of #category to string and then concatenate with the dynamic query
where EventCategory_ID=' + convert(varchar(10), #category)
OR, you pass the value in as a parameter.
for this option, you specify #category in the dynamic query
where EventCategory_ID= #category
and (ParallelStatus=3 ....
and you pass the value in at sp_executesql
EXEC sp_executesql #Event, N'#category int', #category
By the way, Option 2 is the preferred method when using dynamic query

Error unexpected token in stored procedure Advantage Database SQL

I have A stored procedure that is giving me an unexpected Token; ORDER expecting semicolon when I have this statement near the end when I try to execute it.
select year from #temp where year is not null ORDER BY year DESC;
if I remove the ORDER BY year DESC; the procedure works correctly.
I've tried every way possible to sort the resulting table in descending order. I'm fairly new to SQL so I'm sure its something simple. TIA.
// --------- full stored procedure ------ //
ALTER PROCEDURE GetYearForExhaustCatalog
(
CatCodeString Memo,
Year CHAR ( 4 ) OUTPUT
)
BEGIN
/*
EXECUTE PROCEDURE GetYearForExhaustCatalog('(e.catalogcode= ''2182'')');
EXECUTE PROCEDURE GetYearForExhaustCatalog('');
*/
DECLARE #CatCodeString string;
DECLARE #SQL string;
#CatCodeString = (SELECT CatCodeString FROM __input);
if #CatCodeString IS NULL or #CatCodeString = '' then
select e2.year,
(SELECT top 1 e2.year
FROM eenginecatalog e LEFT JOIN exhaustengine e2 ON e2.app_no=e.app_no)
as year
into #temp
from Exhaustengine e2;
select year from #temp where year is not null
GROUP BY year
ORDER BY year DESC;
else
#SQL =
'select e2.year, '+
'(SELECT top 1 e2.year '+
'FROM eenginecatalog e LEFT JOIN exhaustengine e2 ON e2.app_no=e.app_no and '+
#CatCodeString +' ) '+
'as year '+
'into #temp '+
'from Exhaustengine e2; '+
'select year from #temp where year is not null '+
'GROUP BY year '+
'ORDER BY year DESC ';
execute immediate #SQL;
end;
insert into __output
select year from #temp where year is not null ORDER BY year;
drop table #temp;
END;
It seems that ADS does not like the ORDER BY clause when inserting into the special __output table.
This does not work as well:
CREATE PROCEDURE MyProcedure(Year INTEGER OUTPUT)
BEGIN
CREATE TABLE #tmp ("Year" INTEGER);
INSERT INTO #tmp ("Year") VALUES (2019);
INSERT INTO #tmp ("Year") VALUES (2017);
INSERT INTO #tmp ("Year") VALUES (2018);
INSERT INTO
__output
SELECT
"Year"
FROM #tmp
ORDER BY
"Year";
DROP TABLE #tmp;
END;
It fails with the same error message you got:
poQuery: Error 7200: AQE Error: State = 42000; NativeError = 2117; [SAP][Advantage SQL Engine]Unexpected token: ORDER -- Expecting semicolon. -- Location of error in the SQL statement is: 269 (line: 15 column: 1)
As a workaround you can create another temporary table that has the result sorted:
CREATE PROCEDURE MyProcedure(Year INTEGER OUTPUT)
BEGIN
CREATE TABLE #tmp ("Year" INTEGER);
INSERT INTO #tmp ("Year") VALUES (2019);
INSERT INTO #tmp ("Year") VALUES (2017);
INSERT INTO #tmp ("Year") VALUES (2018);
SELECT
*
INTO #sorted
FROM #tmp
ORDER BY
"Year"
;
INSERT INTO
__output
SELECT
"Year"
FROM #sorted;
DROP TABLE #sorted;
DROP TABLE #tmp;
END;
This works without errors and the data is sorted.
The __output table is not the culprit. In SQL standard, ORDER BY is not allowed in sub-queries in general. The reason is that sorting a set of rows should have no effect during the internal resolution of a query. It is only useful in the final result. In pure SQL sense, the only action that guarantees the result is sorted is the ORDER BY on the final result.
If you follow this logic, the possible alternative is not to try to put the data into the __output table in sorted order but to make final output sorted with the following:
SELECT * FROM (EXECUTE PROCEDURE MyProcedure(inParam)) t ORDER BY t.year

error in sql query result

I have this query
DECLARE #Base nvarchar(200)
SET #Base = 'WITH Base AS (SELECT Id, ROW_NUMBER() OVER (ORDER BY Id DESC) RN FROM'
+ Quotename(#SampleWorkTbl) + ')
SELECT * INTO ##temp FROM Base'
EXEC (#Base)
SELECT * FROM ##temp
declare #command nvarchar(max)
Set #command='SELECT TOP 15 [Name],[ImageAddress],(SELECT TOP 1 COUNT(Id) FROM' + QUOTENAME(#SampleWorkTbl) + ') as AllSampleCount FROM ' + QUOTENAME(#SampleWorkTbl) +
' WHERE [Id] IN (SELECT TOP 15 Id From ##temp WHERE RN > ((#Count-1)*15) ORDER BY Id DESC) ORDER BY Id DESC'
exec (#command)
drop table ##temp
I want get [Name],[ImageAddress] and count of Id from any table name that pass to the procedure
but instead of get name , image address and Id I get this data
Id RN
10 1
9 2
8 3
7 4
6 5
5 6
4 7
3 8
2 9
1 10
and when try again i get this error
There is already an object named '##temp' in the database.
#SampleWorkTbl is a name of any table that pass to the this query
how i can fix this problem ?
thank you for you help
Your Query is executing until
EXEC (#Base)
You are getting the
There is already an object named '##temp' in the database.
at
SELECT * FROM ##temp
means you got error somewhere and it didn't reached the point
drop table ##temp
as #Ganesh_Devlekar mentioned
Try adding
if (object_ID('tempdb..##temp')) is not NULL
DROP TABLE ##temp
at the Starting
try this:
For
There is already an object named '##temp' in the database.
Before Creating New Temp Table You need to Use This:
if (object_ID('tempdb..##temp')) is not NULL
DROP TABLE ##temp
You need to add [Name],[ImageAddress],ID these columns to get desire output
SET #Base = 'WITH Base AS (SELECT [Name],[ImageAddress],ID,COUNT(ID) CntID, ROW_NUMBER() OVER (ORDER BY Id DESC) RN FROM'
+ Quotename(#SampleWorkTbl) + ' GROUP BY [Name],[ImageAddress],ID)
SELECT * INTO ##temp FROM Base'

Simple SQL code in EXEC throwing an error

This is in relation to my previous question. I am running a exec statement as below and I get an error Incorrect syntax near '+#dbname+'. Any help is greatly appreciated. Thanks.
exec('
declare #dbname nvarchar(100)
set #dbname = ''HUM_FM_1_SYNTQ_TEST''
select #dbname
Select seriesvariables_value from
(
select *, row_number() over
(order by SeriesVariables_ID asc) as rownum from ''+#dbname+''
.dbo.Seriesvariables where
SeriesVariables_Label = ''Enter Tablet Segment Pull Date'' and
Series_ID = 42) as tbl1
where rownum = 1')
It looks like you are trying to dynamically choose what database you're running this query on. You can do when you are creating the query your are going to exec, but you can't have a variable in your query that represents the database.
This should work
declare #dbname nvarchar(100)
set #dbname = 'HUM_FM_1_SYNTQ_TEST'
exec('
select #dbname
Select seriesvariables_value from
(
select *, row_number() over
(order by SeriesVariables_ID asc) as rownum from '+#dbname+'
.dbo.Seriesvariables where
SeriesVariables_Label = ''Enter Tablet Segment Pull Date'' and
Series_ID = 42) as tbl1
where rownum = 1')