I have this stored procedure:
ALTER Procedure [dbo].[sp_Prd_Dashboard_Summary]
(#Period AS INT)
AS
SELECT
SiteName AS SiteName,
MAX(Country) AS Country,
BudgetPrj,
MAX(PeriodEnd) AS PeriodEnd,
MAX(DaysMtd) AS DaysMtd,
MAX(ToGoMtd) AS ToGoMtd,
MAX(PeriodToTDays) AS PeriodToTDays,
SUM(MTDRevenue) AS MtdRev,
SUM(MTDRevenue) / NULLIF(MAX(DaysMTD), 0) * MAX(PeriodToTDays) AS PrjRevenue,
SUM(BdgRevenue) AS BdgRev, SUM(TrgRevenue) AS TrgRev,
SUM(BCMMtd) AS BCMMtd, SUM(HrsMtd) AS HrsMTD,
SUM(FuelVal) AS FuelVal, SUM(FuelLtrs) AS FuelLtrs,
SUM(FuelVal) / NULLIF(SUM(MTDRevenue), 0) AS FuelPerc
FROM
(SELECT
St.SiteName as SiteName,
St.Country as Country,
Null as BudgetPrj, Prd.PeriodEnd as PeriodEnd,
Day(GetDate()) as DaysMtd,
Prd.PeriodNoDays - Day(GetDate()) as ToGoMtd,
Prd.PeriodNoDays as PeriodToTDays,
0 as MTDRevenue, 0 as BdgRevenue,
0 as TrgRevenue, 0 as BCMMtd,
0 as HrsMtd, 0 as FuelVal,
0 as FuelLtrs
FROM
Periods Prd
JOIN
Sites St ON Prd.PeriodSiteID = St.SiteId
WHERE
Prd.Period = #Period AND St.SiteActive = 1
UNION All
Select SiteName as SiteName
, Dit.Country as Country
, Null as BudgetPrj
, Null as PeriodEnd
, 0 DaysMtd
, 0 as ToGoMtd
, 0 as PeriodToTDays
, IIF(Dit.Wcode = 101,
IIF(DiT.WBillMeth = 'Hours', DiT.Hrs * DiT.OpBill,
IIF(DiT.WBillMeth = 'BCM', Loads * DiT.ModelSize * DiT.WBillRate,
IIF(DiT.WBillMeth = 'Cost Plus', (DiT.Hrs * (DiT.OwnBill + DiT.OpBill)) +
(DiT.ShiftHrs * DiT.EmpBill),0))),0) as MTDRevenue
, 0 as BdgRevenue
, 0 as TrgRevenue
, IIF(DiT.WBillMeth = 'BCM', Loads * DiT.ModelSize, 0) as BCMMtd
, IIF(Dit.Wcode = 101,
IIF(DiT.WBillMeth <> 'BCM', DiT.Hrs, 0),0) as HrsMtd
, DiT.Fuel * DiT.FuelRate as FuelVal
, DiT.Fuel as FuelLtrs
From DataInputTotal DiT
Where DiT.Period = #Period and DiT.SiteActive = 1
Union All
Select SiteName as SiteName
, St.Country as Country
, Bdgt.BudgetProject as BudgetPrj
, Prd.PeriodEnd as PeriodEnd
, 0 as DaysMtd
, 0 as ToGoMtd
, 0 as PeriodToTDays
, 0 as MTDRevenue
, PrjRev as BdgRevenue
, BudgTarget as TrgRevenue
, 0 as BCMMtd
, 0 as HrsMtd
, 0 as FuelVal
, 0 as FuelLtrs
From Budget Bdgt Join
Sites St on Bdgt.SiteId = St.SiteId Join
Periods Prd on Bdgt.Period = prd.Period and Bdgt.SiteId = Prd.PeriodSiteID
Where Bdgt.Period = #Period and St.SiteActive = 1
) a
Group By SiteName, BudgetPrj
I am trying to call the procedure and insert the result into a temp table with the below script:
Declare #Period int = 22
Declare #DaysinMonth Int = 29
Declare #DayHrs Int = 24
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
Create Table #Temp (SiteName nvarchar(50)
, Country nvarchar(50)
, BudgetPrj nvarchar(50)
, PeriodEnd DateTime
, DaysMtd Int
, ToGoMtd Int
, PeriodToTDays Int
, MtdRev Numeric(13,2)
, PrjRevenue Numeric(13,2)
, BdgRev Numeric(13,2)
, TrgRev Numeric(13,2)
, BCMMtd Numeric(13,2)
, HrsMtd Numeric(13,2)
, FuelVal Numeric(13,2)
, FuelLtrs Numeric(13,2)
, FuelPerc Numeric(13,2)
, FltCnt Int
, Availibility Numeric(13,2)
, Utilization Numeric(13,2)
, Idle Numeric(13,2)
)
Insert #temp
Exec sp_Prd_Dashboard_Summary #Period
Insert into #temp
Exec summary_fleet_performance #DayHrs, #Period, #DaysinMonth
When running the script I get the following error:
Column name or number of supplied values does not match table definition.
I have checked the aliases of the SELECT and all columns have names.
I ended creating two temp tables and inserting each stored procedure into each table and then joining them.
It worked perfectly for me:
ALTER Procedure [dbo].[summary_dashboard]
(
#Period int,
#DaysinMonth Int,
#DayHrs Int
)
as
Declare #Tbl1 as table (SiteName nvarchar(50) null
, Country nvarchar(50) null
, BudgetPrj nvarchar(50) null
, PeriodEnd DateTime null
, DaysMtd Int null
, ToGoMtd Int null
, PeriodToTDays Int null
, MtdRev Numeric(13,2) null
, PrjRevenue Numeric(13,2) null
, BdgRev Numeric(13,2) null
, TrgRev Numeric(13,2) null
, BCMMtd Numeric(13,2) null
, HrsMtd Numeric(13,2) null
, FuelVal Numeric(13,2) null
, FuelLtrs Numeric(13,2) null
, FuelPerc Numeric(13,2) null
)
Declare #Tbl2 as Table (SiteName nvarchar(50) null
, FltCnt Int null
, Availability Numeric (5,2) null
, Utilization Numeric (5,2) Null
, Idle Numeric(5,2)
)
insert into #Tbl1 (SiteName
, Country
, BudgetPrj
, PeriodEnd
, DaysMtd
, ToGoMtd
, PeriodToTDays
, MtdRev
, PrjRevenue
, BdgRev
, TrgRev
, BCMMtd
, HrsMtd
, FuelVal
, FuelLtrs
, FuelPerc
)
Exec sp_Prd_Dashboard_Summary #Period
insert into #tbl2 (SiteName
, FltCnt
, Availability
, Utilization
, Idle
)
Exec summary_fleet_performance #DayHrs, #Period, #DaysinMonth
select tbl1.SiteName
, tbl1.Country
, tbl1.BudgetPrj
, tbl1.PeriodEnd
, tbl1.DaysMtd
, tbl1.ToGoMtd
, tbl1.PeriodToTDays
, tbl1.MtdRev
, tbl1.PrjRevenue
, tbl1.BdgRev
, tbl1.TrgRev
, tbl1.BCMMtd
, tbl1.HrsMtd
, tbl1.FuelVal
, tbl1.FuelLtrs
, tbl1.FuelPerc
, tbl2.FltCnt
, tbl2.Availability
, tbl2.Utilization
, tbl2.Idle
from #tbl1 tbl1 full outer join
#tbl2 tbl2
on tbl1.SiteName = tbl2.SiteName
TRY THIS: Your stored procedure is returning 14 columns and temporary table has more than that so you have to mention columnS in the INSERT INTO #TEMP as below and if you are not specifying the columns name of table then returning columns from the STORED PROCEDURE also must be same.
INSERT INTO #temp(SiteName
, Country
, BudgetPrj
, PeriodEnd
, DaysMtd
, ToGoMtd
, PeriodToTDays
, MtdRev
, PrjRevenue
, BdgRev
, TrgRev
, BCMMtd
, HrsMtd
, FuelVal
, FuelLtrs)
Exec sp_Prd_Dashboard_Summary #Period
The temporary table to which you are trying to insert rows contains more columns than the result from stored procedure. Provide column names in insert query, like this:
Insert into table(Column1, Column2....)
Related
I need to update temp table in sql 2014 but this code seems wrong .
first i select all invoices and its Qty from invoices and set Inventory Qty with 0. and second statement i need to update each line by qty of inventory to compare later and use this code.declare #DifferenceTable table (
DataAreaId nvarchar(10) ,
SalesId nvarchar(50) ,
InvoiceId nvarchar(50) ,
ItemId nvarchar(50),
InvoiceQty decimal(16,4) ,
InventoryQty decimal(16,4)
)
insert into #DifferenceTable (DataAreaId , SalesId , InvoiceId , ItemId , InvoiceQty , InventoryQty )
select CustInvoiceTrans.DATAAREAID , CustInvoiceTrans.SALESID , CustInvoiceTrans.INVOICEID , CustInvoiceTrans.ITEMID , sum(CustInvoiceTrans.QTY) , 0. as InventoryQty
from CustInvoiceTrans with(nolock)
group by CustInvoiceTrans.DATAAREAID , CustInvoiceTrans.SALESID , CustInvoiceTrans.INVOICEID , CustInvoiceTrans.ITEMID
update #DifferenceTable
set InventoryQty = tt.Qty from
(select sum(InventTrans.QTY)*-1 as Qty , InventTransOrigin.DATAAREAID , REFERENCEID , InventTrans.INVOICEID , InventTrans.ITEMID
from InventTransOrigin
left join InventTrans on InventTrans.INVENTTRANSORIGIN = InventTransOrigin.RECID
and InventTrans.DATAAREAID = InventTransOrigin.DATAAREAID
and InventTrans.ITEMID = InventTransOrigin.ITEMID
where REFERENCECATEGORY = 0
group by InventTransOrigin.DATAAREAID , REFERENCEID , InventTrans.INVOICEID , InventTrans.ITEMID
) tt
where #DifferenceTable.DataAreaId = tt.DATAAREAID and #DifferenceTable.SalesId = tt.REFERENCEID
and tt.INVOICEID = #DifferenceTable.InvoiceId and tt.ITEMID = #DifferenceTable.ItemId
select * from #DifferenceTable`
My goal is to get the price from item which goes into stock and put the price into out item by (FIFO order by TranDate), then calculate the total price of any line of production (" lineid ").
This is what I have done
-- temp table for result
declare #Test table ( stockID int , OriQty decimal(16,2) ,inuse decimal(16,2) , price decimal(16,2) , lineid int , Inid int )
declare #StockIn table (ID int , StockID int ,qty decimal(16,2),Price decimal(16,2), tranDate Date , running int)
insert into #StockIn(ID , StockID , qty , Price , tranDate , running) values
(1,1 , 15 , 430 , '2014-10-09' , 1),
(2,1 , 10 , 431, '2014-12-09' , 2),
(3,1 , 15 , 432, '2015-02-02' , 3),
(4,2 , 15 , 450, '2014-08-05' , 1),
(5,2 , 6 , 450, '2014-10-09' , 2),
(6,2 , 15 , 452, '2015-02-02' , 3)
-- lineid = line production
declare #StockOut table (ID int , StockID int ,qty decimal(16,2), lineid int, tranDate Date)
insert into #StockOut(ID , StockID ,qty , lineid, tranDate )
values
(1,1 , 20 , 2, '2014-10-10'),
(2,1 , 10 , 4, '2014-12-20'),
(3,2 , 12 , 8, '2014-10-01'),
(4,2 , 3 , 8, '2014-10-01') ;
DECLARE #intFlag INT
SET #intFlag = 1 -- initial of loop
WHILE (#intFlag <= (Select Max(ID) from #StockOut) )
BEGIN
declare #stockID int
declare #ids table (ID int , Inuse decimal(16,2))
declare #lineid int
declare #qtyToRemove decimal(16,2) -- get qty from #StockOut
--get data from #StockOut row by row
select #stockID = StockID , #qtyToRemove = qty , #lineid = lineid from #StockOut where ID = #intFlag;
with cte as (
select *, sum(qty) over (order by tranDate ASC , qty DESC , tranDate ASC Rows UNBOUNDED PRECEDING) - #qtyToRemove
as Total FROM #StockIn Where stockID = #stockID )
-- running FIFO from #StockIn and update QTy when stock is running out
, RunningFIFO as (
select cte.StockID , cte.qty AS OriginalQty , Case when
case when 0 > total then cte.qty else cte.qty-total End > 0 then case when 0 > total then cte.qty else cte.qty-total End else 0 End As Inuse
, cte.Price , #lineid AS lineid , id
from cte
)
-- insert result into result table
insert into #test (stockID , OriQty ,inuse , cte.Price , lineid ,Inid ) OUTPUT inserted.Inid , inserted.inuse into #ids select * from RunningFIFO Where Inuse > 0
UPDATE #StockIn set qty = qty - inuse from #ids A inner join #StockIn B on A.ID = b.ID
SET #intFlag = #intFlag + 1
END
Select sum(inuse * price) AS total , lineid from #Test group by lineid
But when data are more than a thousand, this query runs super slow.
How could I increase the performance of this query?
SELECT
*
FROM tblName
WHERE mode = '1' AND (category = #Category OR #Category = 'all' OR NewsId = #Category)
I passed #Category='all'. This returns 0 rows. If OR NewsId=#Category this condition not added, query will return all results
Try this one -
mode = '1'
AND
(
#Category = 'all'
OR
#Category IN (category, CAST(NewsId AS VARCHAR(10)))
)
Do not use too large data-type length (i mean MAX):
CREATE TABLE dbo.TBL_ContentsPage
(
NewsId INT IDENTITY(1001,1) NOT NULL PRIMARY KEY
, Header NVARCHAR(1024) NULL
, SmallImage IMAGE NULL
, TextContent NVARCHAR(2048) NULL
, PostedDate DATETIME NOT NULL DEFAULT(GETDATE())
, mode VARCHAR(50) NULL
, [status] VARCHAR(50) NULL
, category VARCHAR(200) NULL
, author NVARCHAR(1024) NULL
, imgRefID VARCHAR(50) NULL
)
ALTER PROCEDURE [dbo].[SPGetArticlePaging]
(
#startposition INT
, #stopposition INT
, #Category VARCHAR(200)
)
AS BEGIN
SELECT
NewsId
, Header
, TextContent
, author
, PostedDate
, category
, imgRefID
FROM (
SELECT
NewsId
, Header
, TextContent
, author
, PostedDate
, category
, DateRank = ROW_NUMBER() OVER(ORDER BY PostedDate DESC)
, imgRefID
FROM dbo.TBL_ContentsPage
WHERE mode = '1'
AND
(
#Category = 'all'
OR
#Category IN (category, CAST(NewsId AS VARCHAR(10)))
)
) t
WHERE DateRank BETWEEN #startposition AND #stopposition
RETURN 0
END
I am trying to do a insert into select from a temp table. My problem is that I need to insert the items and also retrieve IDs of the inserted items in the insert statement.
How do I get the list of identity values that were inserted?
The code is below:
SELECT O.OrderID,
O.SingleAgreementID ,
O.OrderTypeID ,
O.OrderStatusID ,
O.Reference ,
O.CreateDate ,
O.ValidityDate ,
O.DeliveredDate ,
O.PathologyID ,
O.DiscountTypeID ,
O.DiscountAmount ,
O.ValidityDays ,
O.DeductibleTypeID ,
O.DeductibleAmount ,
O.LimitOrder ,
O.Comments ,
O.CreatedUserID ,
O.StartPeriodDate ,
O.EndPeriodDate ,
O.GenerationDay ,
O.ParentOrderID ,
O.CanceledDate ,
O.CanceledUserID INTO #TEMPORDERS
FROM dbo.[Order] O
WHERE O.GenerationDay = DAY(GETDATE() -1)
AND O.OrderTypeID = 2
AND #Yesterday BETWEEN CONVERT(VARCHAR(10),O.StartPeriodDate,111) AND CONVERT(VARCHAR(10),O.EndPeriodDate,111)
INSERT INTO dbo.[Order]
( SingleAgreementID ,
OrderTypeID ,
OrderStatusID ,
Reference ,
CreateDate ,
ValidityDate ,
DeliveredDate ,
PathologyID ,
DiscountTypeID ,
DiscountAmount ,
ValidityDays ,
DeductibleTypeID ,
DeductibleAmount ,
LimitOrder ,
Comments ,
CreatedUserID ,
StartPeriodDate ,
EndPeriodDate ,
GenerationDay ,
ParentOrderID ,
CanceledDate ,
CanceledUserID
)
SELECT TEMP.SingleAgreementID ,
TEMP.OrderTypeID ,
1 ,
TEMP.Reference ,
TEMP.CreateDate ,
GETDATE() + TEMP.ValidityDays,
NULL ,
TEMP.PathologyID ,
TEMP.DiscountTypeID ,
TEMP.DiscountAmount ,
TEMP.ValidityDays ,
TEMP.DeductibleTypeID ,
TEMP.DeductibleAmount ,
TEMP.LimitOrder ,
TEMP.Comments ,
'Orden Generada de manera automatica' ,
TEMP.StartPeriodDate ,
TEMP.EndPeriodDate ,
TEMP.GenerationDay ,
TEMP.OrderID ,
NULL ,
NULL
FROM #TEMPORDERS TEMP
--Get all Ids inserted HERE
SELECT SCOPE_IDENTITY();
--Get the IDs saved and insert the detail.
I don't know whether that is possible or not? Any ideas on this?
Thanks.
You can use Output to fill a table with th new ID's
Declare #OutputTable table(aNewid int)
Insert into Table
........
Output inserted.ID
Select ....
from InputTable
Try this one -
INSERT INTO dbo.[Order] (
SingleAgreementID
, OrderTypeID
, OrderStatusID
...
)
OUTPUT INSERTED.[IdentityColumn] INTO #temp1
SELECT t.SingleAgreementID
, t.OrderTypeID
, 1
...
FROM #TEMPORDERS t
SELECT * FROM #temp1
I have the below code. It basically takes values from a spreadsheet loaded in by an asp.net upload control. A document number is automatically assigned. I put the data into a temp table, and then select and insert the data from the temp table into my actual database table. The data is group so that it takes the minimum doc number, and date column (the ONLY columns that are different for the data). The data loads fine but for some reason it does not get grouped. Does anyone see any problems with the query itself?
CREATE Procedure dbo.temptable
(
#DocumentBranchPlant varchar(12)
, #DocumentType varchar(2)
, #DEANumber varchar(9)
, #DebitMemo varchar(25)
, #DebitTotal float
, #ErrorOverRide bit
, #OnHold bit
, #LastModifiedUser varchar(50)
, #ResubmissionCode char(2)
, #DocumentNumber float out
)
AS
begin
declare #TransmissionDate datetime
declare #JulianTransmissionDate numeric(18,0)
declare #ShipTo float
declare #CustomerName varchar(40)
Set #DocumentNumber = scope_identity()
set #TransmissionDate = getdate()
set #JulianTransmissionDate =getdate()
DECLARE #cb table
( DocumentBranchPlant char(12)
, DocumentNumber float
, DocumentType char(2)
, JulianTransmissionDate numeric(18,0)
, TransmissionDate datetime
, DEANumber varchar(9)
, ShipTo float
, DebitMemo char(25)
, DebitTotal float
, CustomerName varchar(40)
, ErrorOverRide bit
, EntryComplete bit
, OnHold bit
, ManualEntry bit
, LastModifiedUser varchar(50)
, LastModifiedDate datetime
, ResubmissionCode char(2))
INSERT INTO #cb
( DocumentBranchPlant
, DocumentNumber
, DocumentType
, JulianTransmissionDate
, TransmissionDate
, DEANumber
, ShipTo
, DebitMemo
, DebitTotal
, CustomerName
, ErrorOverRide
, EntryComplete
, OnHold
, ManualEntry
, LastModifiedUser
, LastModifiedDate
, ResubmissionCode)
VALUES
( #DocumentBranchPlant
, #DocumentNumber
, #DocumentType
, #JulianTransmissionDate
, #TransmissionDate
, #DEANumber
, #ShipTo
, #DebitMemo
, #DebitTotal
, #CustomerName
, #ErrorOverRide
, 0
, #OnHold
, 1
, #LastModifiedUser
, getdate()
, #ResubmissionCode)
INSERT INTO dbo.CbTempTable
( DocumentBranchPlant
, DocumentNumber
, DocumentType
, JulianTransmissionDate
, TransmissionDate
, DEANumber
, ShipTo
, DebitMemo
, DebitTotal
, CustomerName
, ErrorOverRide
, EntryComplete
, OnHold
, ManualEntry
, LastModifiedUser
, LastModifiedDate
, ResubmissionCode)
SELECT
DocumentBranchPlant
, min(DocumentNumber)
, DocumentType
, JulianTransmissionDate
, min(TransmissionDate)
, DEANumber
, ShipTo
, DebitMemo
, DebitTotal
, CustomerName
, ErrorOverRide
, EntryComplete
, OnHold
, ManualEntry
, LastModifiedUser
, min(LastModifiedDate)
, ResubmissionCode
FROM #cb
GROUP BY
DocumentBranchPlant
, DocumentType
, JulianTransmissionDate
, DEANumber
, ShipTo
, DebitMemo
, DebitTotal
, CustomerName
, ErrorOverRide
, EntryComplete
, OnHold
, ManualEntry
, LastModifiedUser
, ResubmissionCode