This may be a dumb question, but I can't seem to get the syntax right. I have two temp tables that have the same columns, I want to do a union on them and store the results in a temp table. Any ideas?
Ie.
select * from #tmpTable1
union
select * from #tmpTable2
into #tmpTable3
Hi, I have follwing union query. I want to put this all in a temp table.
select Store_Id,batchnumber From Adjustments where updatedDt between '10/30/2007' and '11/20/2007' and Store_id in(8637 ,8641) group by Store_Id, batchnumber Union select DestinationId,b.batchNumber from batch b inner join Carton C on C.Carton_Id = b.General_ID inner join Document d on d.Document_Id = c.Document_Id where b.BatchType = 'Warehouse' and b.TranTable = 'Carton' and (d.DestinationId in (8637 ,8641) ) and c.UpdatedDt Between '10/30/2007' and '11/20/2007' Union select d.DestinationId,b.Batchnumber From batch b inner join Document d on d.Document_Id = b.General_Id where b.BatchType = 'TransferIn' and b.TranTable = 'Document' and (d.DestinationId in (8637,8641) ) and d.UpdatedDt Between'10/30/2007' and '11/20/2007' Union select d.SourceId,b.batchNumber From batch b inner join Document d on d.Document_Id = b.General_Id where b.BatchType = 'TransferOut' and b.TranTable = 'Document' and (d.SourceId in (8637,8641) ) and d.UpdatedDt Between'10/30/2007' and '11/20/2007' order by batchnumber
Right now, a client of mine has a T-SQL statement that does thefollowing:1) Create a temp table.2) Populate temp table with data from one table using an INSERTstatement.3) Populate temp table with data from another table using an INSERTstatement.4) SELECT from temp table.Would it be more efficient to simply SELECT from table1 then UNIONtable 2? The simply wants to see the result set and does not need tore-SELECT from the temp table.
I'm having trouble creating a temp table out of a select statement that uses multipe union alls.
Here's what I have, I'm trying to get the results of this query into a temp table...
select parent, (select cst_id from co_customer (nolock) where cst_key = Parent) as cst_id, (select cst_name_cp from co_customer (nolock) where cst_key = Parent) as cst_name_cp, (select org_total_assets_ext from dbo.co_organization_ext where org_cst_key_ext = parent) as Parent_Total_assets, sum(own_assets) as Total_child_own_assets
from ( Select parent, Child, (select org_own_assets_ext from dbo.co_organization_ext where org_cst_key_ext = child) as Own_assets
from (Select Cst_key as Child, dbo.return_org_parent(cst_key,0,1) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,1) is not null union all
Select Cst_key as Child, dbo.return_org_parent(cst_key,0,2) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,2) is not null union all
Select Cst_key as Child, dbo.return_org_parent(cst_key,0,3) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,3) is not null union all
Select Cst_key as Child, dbo.return_org_parent(cst_key,0,4) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,4) is not null union all
Select Cst_key as Child, dbo.return_org_parent(cst_key,0,5) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,5) is not null union all
Select Cst_key as Child, dbo.return_org_parent(cst_key,0,6) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,6) is not null union all Select Cst_key as Child, dbo.return_org_parent(cst_key,0,7) as Parent from co_customer (nolock) where cst_type = 'Organization' and cst_delete_flag = 0 and dbo.return_org_parent(cst_key,0,7) is not null )as c ) as d
group by parent
having sum(own_assets) <> (select org_total_assets_ext from dbo.co_organization_ext where org_cst_key_ext = parent)
I'm writing a search engine and I want to make a search and then, after I've recieved the results, put them into some sort of temporary(in mememory) table so that I can do another query on that temporary table.
I saw something about temp tables (in T-SQL) in the help guide, but I still want to know how to do a query on a regular table and then store those results in a temporary table to perform a query on that. Could anyone show me some example or something?
Does anyone know if the results from a query run in QA automatically go into a tempoary table? For instance if ive just run a query that took 5 minutes but it was a normal select query and after it ran i realised i wanted to query the results could i run a simple command to mke a copy of the result set rather than run the original query into a temp table that would then take a few minutes again?
I'm trying to fill a temp table whose columns are the same as another table plus it has one more column. The temp table's contents are those rows in the other table that meet a particular condition plus another column that is the name of the table that is the source for the rows being added.
Example: 'permTable' has col1 and col2. The data in these two rows plus the name of the table from which it came ('permTable' in this example) are to be added to #temp.
Data in permTable col1 col2 11, 12 21, 22
Data in #temp after permTable's filtered contents have been added
I pulled some examples of using a subquery pivot to build a temp table, but cannot get it to work.
IF OBJECT_ID('tempdb..#Pyr') IS NOT NULL DROP TABLE #Pyr GO SELECT vst_int_id, [4981] AS Primary_Ins, [4978] AS Secondary_Ins,
[code]....
The problems I am having are with the integer data being used to create temp table fields. The bracketed numbers on line 7-10 give me an invalid column name error each. In the 'FOR', I get another error "Incorrect syntax near 'FOR'. Expecting '(', or '.'.". The first integer in the "IN" gives me an "Incorrect syntax near '[4981]'. Expecting '(' or SELECT". I will post the definitions from another effort below.
I have 2 temporary tables from a previous operation, Tab1 and Tab2, with the same dimensions. How do I create a third table Tab3 with the same dimensions containing the the combined rows of the 2 previous tables? TIA!
I'm trying to summarize costs assigned to active jobs for a manufacturing business. I need to aggregate work in process (WIP) cost that resides in labor-transaction and part-transaction tables based on transaction types, and transaction dates. Some transactions increase the WIP cost of the job while others decrease WIP. The business needs to see how much $$ is tied up in each job as of a particular date -- the calculation is: ToDate (cost of materials and labor assigned to job) - ToInv (cost of materials returned to inventory) - ToSales (cost of materials sold).
I developed this query incrementally and, so far, the #ToDate, #ToInv, and #ToSales temp tables seem to be populating with the correct data. My thought was to combine these three tables with a UNION and then extract the grand totals and here's where I started getting the following error: ------------------------------------------ Incorrect syntax near the keyword 'UNION'. ------------------------------------------ The problem is with the UNIONs going into #myTotal.
I would appreciate any help with this. Also, please let me know if you can suggest a better design for this. Thanks!
--M&S To Date SELECT pt.jobnum, SUM(pt.extcost) AS Cost FROM parttran pt JOIN jobhead jh ON pt.jobnum=jh.jobnum WHERE trantype IN ( <valid trans types> ) AND jh.JobReleased = 1 AND pt.TranDate < '2007-9-30' GROUP BY pt.jobnum
UNION -- This one works ok.
--L&B To Date SELECT jh.JobNum, sum(l.LaborRate*l.LaborHrs) + sum(l.BurdenRate*l.BurdenHrs) AS Cost FROM LaborDtl l JOIN JobHead jh ON l.JobNum = jh.JobNum WHERE jh.JobReleased = 1 AND l.PayrollDate < '2007-9-30' GROUP BY jh.JobNum
SELECT pt.jobnum, SUM(pt.extcost) AS ToInv FROM parttran pt JOIN jobhead jh ON pt.jobnum=jh.jobnum WHERE trantype IN (<valid trans types>) AND jh.JobReleased = 1 AND pt.TranDate < '2007-9-30' GROUP BY pt.jobnum
SELECT pt.jobnum, SUM(pt.extcost) AS ToInv FROM parttran pt JOIN jobhead jh ON pt.jobnum=jh.jobnum WHERE trantype IN (<valid trans types>) AND jh.JobReleased = 1 AND pt.TranDate < '2007-9-30' GROUP BY pt.jobnum
I have a problem with a union all that seems to be changing the results of a column based on using the union, when I run the querys separatly I get the expected results in the field!
Basically 3 queries pulled together for reporting purposes.
Orders (which can include a gift so the gifts are separated in the second query). OrderGifts (pulled out of the orders). Gifts (straight gifts with no associated orders).
The problem is showing up in the first ORDERS query. I can pull a specific order and the calculation for the AMOUNT(eg:$15.20) is correct, but when I combine the tables I get a different AMOUNT(eg:$15.199999999999999).
Here are the values for the fields in the amount calc: totitems=12.9500 totcredits=.0000 discount=.0000 tax=.0000 refund=.0000 convrate=1.0 postage=2.2500 giftamt=15.0000
I tried converting each of the fields to an decimal befre the calc and same results
I tried ROUND and same thing!
I have been trying to chase this down all day, cant figure out what the problem is or how to get around it...whats going on here I am missing?
Here is the query, if you need any other info just let me know, I would GREATLY appreciate ANY direction of figuring this out!
select * from ( --orders select acctnbr as PartnerId, 'O' as TrnType, ordnbr as TrnId, 0 as FundId, odate as WorkDate, adate as PostDate, sdate as ShipDate, cast( ( IsNull(totitems, 0) - IsNull(totcredits, 0) - IsNull(discount, 0) - IsNull(tax, 0) - IsNull(refund, 0) + IsNull(postage, 0) ) * IsNull(convrate, 1) as Decimal(10,2)) as Amount, batchnbr as BatchId, motvcode as MotivationCode, currcode as CurrencyType, Status, paycode as PaymentType, paytype as CardType, paynbr as CardNbr, expire as CardExpire, ChargeAuth, ConvRate, MediaCode, hcf.dbo.KmaiProjMotvTest(0,motvcode) as ProjMotvName from kmai.dbo.o01omst
UNION all
--orders gifts select acctnbr as PartnerId, 'G' as TrnType, giftref as TrnId, giftfundid as FundId, odate as WorkDate, null as PostDate, null as ShipDate, ROUND((giftamt * IsNull(convrate, 1)),2) as Amount, batchnbr as BatchId, giftmotvcode as MotivationCode, currcode as CurrencyType, Status, paycode as PaymentType, paytype as CardType, paynbr as CardNbr, expire as CardExpire, ChargeAuth, ConvRate, MediaCode, hcf.dbo.KmaiProjMotvTest(giftfundid,giftmotvcode) as ProjMotvName from kmai.dbo.o01omst where adate is null and giftfundid <> ''
UNION ALL --gifts select acctnbr as PartnerId, 'G' as TrnType, gh.giftref as TrnId, convert(int, fundid) as FundId, gdate as WorkDate, applydate as PostDate, null as ShipDate, ROUND((IsNull(gd.amt, 0) * IsNull(convrate, 1)),2) AS Amount, batchnbr as BatchId, motvcode as MotivationCode, currcode as CurrencyType, Status, paycode as PaymentType, paytype as CardType, paynbr as CardNbr, expire as CardExpire, ChargeAuth, ConvRate, MediaCode, hcf.dbo.KmaiProjMotvTest(fundid,motvcode) as ProjMotvName from kmai.dbo.g03ghdr gh inner join kmai..g04gdtl gd on gh.giftref = gd.giftref
Code: SELECT DISTINCT LEFT([REPORTING_MONTH], 4)+'-'+SUBSTRING([REPORTING_MONTH],5,6) as REPORTING_MONTH, t.EMPLOYEE, '' as COUNT_FTP, CASE WHEN [MEDIUM_RCVD] = 'EMAIL' THEN COUNT(MEDIUM_RCVD) ELSE '' END AS COUNT_EMAIL FROM [GPO].[dbo].[DW_SUBMISSION] as s JOIN #TEMPActivity as t
[Code] ....
I'm trying to get the set to come out all on one line. REPORTING_MONTH, EMPLOYEE, COUNT_FTP, COUNT_EMAIL
But when I try null or '' it creates a second record and doesn't merge the two results.
I've got a union query (below)and it returns rows that have duplivate itemno's, descrip's, imsrp3's, and imsrp4's, while the remaining columns are not duplicate for the same row. An Excel report uses this query to populate itself and for a more visually appealing look, I'd like to skip the duplicated columns in the display. I'm not sure how to use the Distinct or Group by in this case, since technically I'm dealing with two separate queries, neither one separately returning any duplicate rows. thanks for any suggestions...
~ select itemno,descrip,imsrp3,imsrp4,qoh,border,wadcto,wad oco, watrdj,wapddj,wauorg,wauser from nowo where nowo.wasrst <='40' union select itemno,descrip,imsrp3,imsrp4,qoh,border,wadcto,wad oco, watrdj,wapddj,wauorg,wauser from nopo where nopo.wasrst <='499'
How can I UNION two MDX query results which are deriving from 2 cubes?MDX queries will return same ROW information and only Measure names will be different.
I think this is a very simple question, however, I don't know the answer. What is the difference between a regular Temp table and a Global Temp table? I need to create a temp table within an sp that all users will use. I want the table recreated each time someone accesses the sp, though, because some of the same info may need to be inserted and I don't want any PK errors.
i am inserting something into the temp table even without creating it before. But this does not give any compilation error. Only when I want to execute the stored procedure I get the error message that there is an invalid temp table. Should this not result in a compilation error rather during the execution time.?
--create the procedure and insert into the temp table without creating it. --no compilation error. CREATE PROC testTemp AS BEGIN INSERT INTO #tmp(dt) SELECT GETDATE() END
only on calling the proc does this give an execution error
Simple example: declare @tTable(col1 int) insert into @tTable(col1) values (1) select * from @tTable
Works perfectly in SQL Server Management Studio and the database connection is OK to as I may generate PP table using complex (or simple) queries without difficulty.
But when trying to get this same result in a PP table I get an error, idem when replacing table variable by a temporary table.
Message: OLE DB or ODBC error. .... The current operation was cancelled because another operation the the transaction failed.
If on the source I have a new column, the script generated by SqlPackage.exe recreates the table on the background with moving the data into a temp storage. If the table is big, such approach can cause issues.
Example of the script is below: in the source project I added columns [MyColumn_LINE_1] and [MyColumn_LINE_5].
Is there any way I can make it generating an alter statement instead?
BEGIN TRANSACTION; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; SET XACT_ABORT ON; CREATE TABLE [dbo].[tmp_ms_xx_MyTable] ( [MyColumn_TYPE_CODE] CHAR (3) NOT NULL,
[Code] ....
The same script is generated regardless the table having data or not, having a clustered or nonclustered PK.
The SP UserPersist_GetByCriteria does a "SELECT * FROM tbl_User WHERE gender = @Gender AND culture = @Culture", so why am I receiving this error when both tables have the same structure?
The error is being reported as coming from UserPersist_GetByCriteria on the "SELECT * FROM tbl_User" line.
I have a query which does 3 selects and Union ALLs each to get a final result set. The performance is unacceptable - takes around a minute to run. If I remove the Union All so that the result sets are returned individually it returns all 3 from the query in around 6 seconds (acceptable performance).
Any way to join the result sets together without using Union All.
Each result set has exactly the same structure returned...
Query below [for reference]...
WITH cte AS ( SELECT A.[PoleID], ISNULL(B.[IsSpanClear], 0) AS [IsSpanClear], B.[SurveyDate], ROW_NUMBER() OVER (PARTITION BY A.[PoleID] ORDER BY B.[SurveyDate] DESC) rownum FROM[UT_Pole] A LEFT OUTER JOIN [UT_Surveyed_Pole] B ON A.[PoleID] = B.[PoleID]