Create a SQL Stored Procedure with Dynamic Column Names - sql-server

I have the following stored procedure:
ALTER PROCEDURE [dbo].[sp_RequestCategoryCount]
#StDate1 DATE,
#EnDate1 DATE,
#StDate2 DATE,
#EnDate2 DATE
AS
BEGIN
SELECT DISTINCT RQ.request_category
INTO #ReqCat
FROM
(SELECT DISTINCT request_category
FROM [VerInt_OneViewServiceReq]
UNION ALL
SELECT DISTINCT request_category
FROM [VerInt_OneViewServiceReq2]) RQ
SELECT
'1' as Iteration,
request_category,
SUM(1) AS Record_Count
INTO
#Iter1
FROM
[VerInt_OneViewServiceReq]
WHERE
request_created_dt BETWEEN #StDate1 AND #EnDate1
GROUP BY
request_category
-- UNION ALL
SELECT
'2' as Iteration,
request_category,
SUM(1) as Record_Count
INTO
#Iter2
FROM
[VerInt_OneViewServiceReq2]
WHERE
request_created_dt BETWEEN #StDate2 AND #EnDate2
GROUP BY
request_category
-- ORDER BY Iteration, request_category ASC
SELECT
RC.request_category,
IT1.Record_Count as RecordCountDateRange1,
IT2.Record_Count as RecordCountDateRange2
FROM
#ReqCat RC
LEFT JOIN
#Iter1 IT1 ON IT1.request_category = RC.request_category
LEFT JOIN
#Iter2 IT2 ON IT2.request_category = RC.request_category
DROP TABLE #ReqCat
DROP TABLE #Iter1
DROP TABLE #Iter2
END
All it does is basically compare 2 timespans of data in 2 tables by lining them up side-by-side, and works fine.
What I'd like to do is replace this from the last SELECT statement:
SELECT
RC.request_category,
IT1.Record_Count as RecordCountDateRange1,
IT2.Record_Count as RecordCountDateRange2
FROM
#ReqCat RC
with something that would "air code" like this:
SELECT
RC.request_category,
IT1.Record_Count AS "#StDate1_to_#EnDate1",
IT2.Record_Count AS "#StDate2_to_#EnDate2"
FROM
#ReqCat RC
so that the field names would indicate the dates used in the comparison.
Is this possible to do without re-writing the whole procedure, and, if so, how would I do it?

Yes, this is possible by using dynamic SQL. I cannot test it but more or less it should work as you specified. It will show on screen (messages area) the sentence being run and you can adjust the SELECT #SQL = ... as per your convenience until you find your correct statement:
ALTER procedure [dbo].[sp_RequestCategoryCount]
#StDate1 date,
#EnDate1 date,
#StDate2 date,
#EnDate2 date
AS
BEGIN
DECLARE #SQL AS NVARCHAR(MAX);
SELECT distinct RQ.request_category
into #ReqCat
FROM ( Select distinct request_category from [VerInt_OneViewServiceReq]
UNION ALL
Select distinct request_category from [VerInt_OneViewServiceReq2]
) RQ
Select
'1' as Iteration,
request_category,
Sum(1) as Record_Count
INTO #Iter1
from [VerInt_OneViewServiceReq]
where request_created_dt between #StDate1 and #EnDate1
group by request_category
--UNION ALL
Select
'2' as Iteration,
request_category,
Sum(1) as Record_Count
INTO #Iter2
from [VerInt_OneViewServiceReq2]
where request_created_dt between #StDate2 and #EnDate2
group by request_category
--order by Iteration, request_category ASC
SELECT #SQL = '
Select RC.request_category,
IT1.Record_Count as ['+CONVERT(VARCHAR(10), #StDate1)+'_to_'+CONVERT(VARCHAR(10), #EnDate1)+'],
IT2.Record_Count as ['+CONVERT(VARCHAR(10), #StDate2)+'_to_'+CONVERT(VARCHAR(10), #EnDate2)+']
from #ReqCat RC
LEFT JOIN #Iter1 IT1
ON IT1.request_category = RC.request_category
LEFT JOIN #Iter2 IT2
ON IT2.request_category = RC.request_category'
-- Debug purposes
PRINT #SQL;
EXEC sp_ExecuteSQL #SQL;
Drop Table #ReqCat
Drop Table #Iter1
Drop Table #Iter2
END

Related

How to Insert into temp table Using SubQuery and Select from Temp table

I am trying to insert this data into a temp table
When I add the piece to insert into my temp table with the second result set #Temp
I recieve an incorrect syntax error
Any Ideas?
sql
-- =============================================
-- Author: <Kaven>
-- Create date: <August 2020>
-- Description: Summary Report of [spRPWipManufactureProcessLogR1]
-- Owner : RpData.dll
-- =============================================
ALTER PROCEDURE [dbo].[spRPWipManufactureProcessLogR2]
#FromDate DATE = null,
#ToDate DATE = null,
#Location NVARCHAR(15) =null, --Dropdown --CostCentre
#Operation NVARCHAR(15) = NULL, -- Dropdown --WorkCentre
#JobNumber nvarchar(15) = NULL
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
--EXEC [spRPWipManufactureProcessLogR2] '20200201', '20200301'
IF #Operation = ''
BEGIN
SET #Operation = null
END
IF #JobNumber = ''
BEGIN
SET #JobNumber = NULL
END
IF OBJECT_ID(N'tempdb..#Temppp_WarehouseList') IS NOT NULL
BEGIN DROP TABLE #Temppp_WarehouseList END
SELECT StockCode
INTO #Temppp_WarehouseList
FROM CompanyA..InvMaster
DECLARE
#wh_List NVARCHAR(1000),
#wh_List2 NVARCHAR(1000)
SELECT #wh_List = STUFF((SELECT ',['+l.Warehouse+' QtyOnHand]' FROM CompanyA..InvWhControl l WHERE l.Warehouse IS NOT NULL FOR XML PATH('')),1,1,'')
SELECT #wh_List2 = STUFF((SELECT ',['+l.Warehouse+' QtyOnOrder]' FROM CompanyA..InvWhControl l WHERE l.Warehouse IS NOT NULL FOR XML PATH('')),1,1,'')
--SELECT #wh_List
--SELECT #wh_List2
SELECT ProductID,
FromDate,
ToDate,
QtyBUoM
INTO #TempBuOM
FROM Cetus.dbo.SMDemandForcastDailyHierarchy df
JOIN dbo.SMDemandSourceTypeDef st ON st.pkDFSourceTypeID = df.fkSourceType
WHERE
df.DemandSource = st.pkDFSourceTypeID
AND
df.Parent = st.pkDFSourceTypeID
AND FromDate <= GETDATE()
AND ToDate >= GETDATE()
SELECT * FROM #TempBuOM
SELECT * FROM #Temppp_WarehouseList t
INNER join
(SELECT * FROM
(SELECT Warehouse+' QtyOnHand' 'WarehouseOnHand', Warehouse+' QtyOnOrder' 'WarehouseOnOrder', QtyOnHand,QtyOnOrder,
b.CostCentre AS 'Location',
--b.WorkCentre AS [Operation],
-- arc.Job AS [Job Number],
--FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'HH:mm:ss') AS [Operation Compeleted Time],
-- CONVERT(VARCHAR, FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'yyyy/MM/dd'),100) AS [Operation Compeleted Date],
-- CONVERT(Date, CONVERT(date, arc.DTComplete))AS [Compeleted Date],
df.ProductID AS 'Product ID',
m.Description AS 'Stock Code DESCRIPTION',
arc.QtyToMake AS 'Quantity To Make',
arc.QtyManufactured 'Quantity Manufactured',
df.QtyBUoM AS 'Daily Demand',
inv.QtyOnOrder AS 'Quantity On Order',
inv.QtyOnHand AS 'Stock Levels'
INTO #TEMP -- Error comes here
FROM Cetus..WIPManufactureProcessLog s
LEFT JOIN WIP..WipMaster_Arc arc ON s.JobId = arc.Job
JOIN CompanyA..InvMaster m ON arc.StockCode = m.StockCode
JOIN CompanyA..InvWarehouse inv ON m.StockCode = inv.StockCode
JOIN CompanyA.dbo.BomOperations bo ON m.StockCode = bo.StockCode AND bo.Operation = s.Operation
JOIN CompanyA..BomWorkCentre b ON bo.WorkCentre = b.WorkCentre
JOIN [dbo].SMDemandForcastDailyHierarchy df ON m.StockCode = df.ProductID
JOIN dbo.SMDemandSourceTypeDef st ON st.pkDFSourceTypeID = df.fkSourceType
--EXEC [spRPWipManufactureProcessLogR2] '20190101', '20200201'
Where CONVERT(VARCHAR, FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'yyyy/MM/dd'),100)
BETWEEN ISNULL(#FromDate,CONVERT(VARCHAR, FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'yyyy/MM/dd'),100))
AND ISNULL(#ToDate,CONVERT(VARCHAR, FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'yyyy/MM/dd'),100))
--WHERE FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'HH:mm:ss') >= '2020-02-01'
--AND FORMAT(CAST(CAST(s.Event AS XML).value('(/OperationTrackingLog/TimeStamp)[1]', 'varchar(max)') AS DATETIME),'HH:mm:ss') <= '2020-03-01 '
AND m.WarehouseToUse <>'AA'
AND b.WorkCentre = ISNULL(#Location,b.WorkCentre )
AND b.CostCentre = ISNULL(#Operation,b.CostCentre )
AND arc.Job = ISNULL(#JobNumber,arc.Job) )p
PIVOT (
SUM(QtyOnHand) FOR WarehouseOnHand IN
([BB QtyOnHand],
[16 QtyOnHand],
[IS QtyOnHand],
[MS QtyOnHand],
[MH QtyOnHand],
[AA QtyOnHand],
[BC QtyOnHand],
[PH QtyOnHand],
[P4 QtyOnHand],
[PL QtyOnHand],
[CC QtyOnHand],
[SR QtyOnHand],
[TS QtyOnHand],
[WW QtyOnHand])) AS pvt
PIVOT
(SUM(QtyOnOrder) FOR WarehouseOnOrder IN
([BB QtyOnOrder],
[16 QtyOnOrder],
[IS QtyOnOrder],
[MS QtyOnOrder],
[MH QtyOnOrder],
[AA QtyOnOrder],
[BC QtyOnOrder],
[PH QtyOnOrder],
[P4 QtyOnOrder],
[PL QtyOnOrder],
[CC QtyOnOrder],
[SR QtyOnOrder],
[TS QtyOnOrder],
[WW QtyOnOrder])) AS pvt2 GROUP BY )
AS z on t.StockCode = z.[Product ID]
```sql```
Edit: Added answers in case the #TEMP table is supposed to have the inner query rather than the final pivot results.
Note that the 'code' provided is there to show structure - you'll need to add the slabs of text from above and bug-fix those as normal. The below is to demonstrate how to fix the issue.
That INTO #TEMP is in the middle of a FROM statement (it's not actually the final select) and therefore doesn't work.
If want the final results (e.g., from the pivot) to be stored in the temp table, remove the current 'INTO #TEMP' and put it into the outer query e.g.,
SELECT *
INTO #TEMP
FROM (your whole pivot statement) AS a
or alternatively using a CTE
; WITH CTE AS
(your whole pivot statement)
SELECT *
INTO #Temp
FROM CTE
If, on the other hand, you want to store the results of the inner query (not the pivot) in a temp table, then
run that first (e.g., take out the inner query you have there, into its own statement)
use the #temp table in the bigger query
-- Initial creation of temp table (SQL extracted from your current code)
SELECT Warehouse+' QtyOnHand' (... and rest of fields)
INTO #Temp
FROM Cetus..WIPManufactureProcessLog s
(... and rest of from, and where clauses)
-- And then use that in your pivot
SELECT *
FROM
(SELECT *
FROM #Temppp_WarehouseList t
INNER join #TEMP ON (... matching fields)
) p
PIVOT
(pivot commands etc)

How to get cumulative record In SQL Server?

I have some data in SQL Server in below format.
declare #statement table
(
acctno int,
statDate date,
tod int,
lastDate date
)
insert into #statement select 123,'2018-02-12',567,'2018-01-12'
insert into #statement select 123,'2018-03-12',580,'2018-02-12'
insert into #statement select 123,'2018-04-12',567,'2018-03-12'
--select * from #statement
declare #txn table
(
acct int,
txndate date,
amount int
)
insert into #txn select 123,'2018-02-11',400
insert into #txn select 123,'2018-02-18',400
insert into #txn select 123,'2018-02-25',400
insert into #txn select 123,'2018-03-11',400
insert into #txn select 123,'2018-03-25',400
Result of the both tables similar like below.
]1
Now I want the result as shown here:
and I am trying to get it with this query:
;with cte as
(
select
acctno, statDate, tod, txndate, amount, lastDate
from
#statement
inner join
#txn on acctno = acct
)
select *
from #txn t
left join cte on acct = acctno
and t.txndate between statDate and lastDate
But the result is not being returned as expected - please help me get the desired result.
I think that you can do this more simply
select s.acctno,statDate,tod,txndate,amount,lastDate
from #txn t
Inner join #statement s
On s.acctno = t.acct
And t.txndate Between s.lastDate and s.startDate
You may need to change the BETWEEN to a “<“ for the startDate comparison.
This is a clasical DKNF join :
WITH TD AS(
SELECT T1.acctno, T1.statDate AS StartDate, T1.tod, COALESCE(MAX(T2.statDate), '1-01-01') AS BeforeDate
FROM #statement AS T1
LEFT OUTER JOIN #statement AS T2
ON T1.acctno = T2.acctno AND T1.statDate < T2.statDate
GROUP BY T1.acctno, T1.statDate, T1.tod
)
SELECT acctno, StartDate, tod, txndate, amount
FROM TD
JOIN #txn AS t
ON TD.acctno = t.acct AND txndate <= StartDate AND txndate > BeforeDate

Why I am getting Column Name Missing error

I wrote a SP which will call internally another parameterized SP and output will be store into a physical table.While I am executing Outer SP I am getting following error.
Msg 207, Level 16, State 1, Procedure CBs_LargeExposer, Line 88 [Batch
Start Line 12] Invalid column name 'SlNo'.
I observed, if I execute inner SP in separate window and very next to it if I execute the same outer SP is working fine, after certain time if I execute the same statement(Outer SP) I am getting same error.
ALTER PROCEDURE [dbo].[CBS_GlMapping]
#finYear nvarchar(30)='2019-2020',
#quarter char(5)='Q2',
#Oflag Varchar(6)='O4'
AS
BEGIN
SET NOCOUNT ON;
Declare #QtrStart date,#QtrSEnd date,#FyFrom int,#FyTo int,#BranchId int
select #FyFrom=year(YearBeginDate),#FyTo=Year(YEarEndDate) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
IF(#FyFrom < left(#finYear,4) and #FyTo < Right(#finYear,4))
Begin
print 'Sorry, Recods are not available for the financial year ' + #finYear
return
End
If(#quarter='Q1')
Begin
select #QtrStart=YearBeginDate,#QtrSEnd=EOMONTH(DATEADD(MM,2,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q2')
Begin
select #QtrStart=Dateadd(mm,3,YearBeginDate),#QtrSEnd=EOMONTH(DATEADD(MM,5,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q3')
Begin
select #QtrStart=Dateadd(mm,6,YearBeginDate),#QtrSEnd=EOMONTH(DATEADD(MM,8,YearBeginDate)) from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
If(#quarter='Q4')
Begin
select #QtrStart=DATEADD(month, DATEDIFF(month, 0,Dateadd(mm,-2,YEarEndDate)), 0),#QtrSEnd=YEarEndDate from BranchTable where BranchCode in(select OrgBankCode from OrgDetails)
End
/* To handel the Financial year */
if(left(#finYear,4)<year(#QtrStart) and #quarter<>'Q4')
begin
set #QtrStart = cast(left(#finYear,4) as varchar(4))+'-'+cast(month(#QtrStart) as Varchar(2))+'-'+Cast(day(#QtrStart) as Varchar(2))
set #QtrSEnd = cast(left(#finYear,4) as varchar(4))+'-'+cast(month(#QtrSEnd) as Varchar(2))+'-'+Cast(day(#QtrSEnd) as Varchar(2))
end
if(right(#finYear,4)<year(#QtrStart) and #quarter='Q4')
begin
set #QtrStart = cast(right(#finYear,4) as varchar(4))+'-'+cast(month(#QtrStart) as Varchar(2))+'-'+Cast(day(#QtrStart) as Varchar(2))
set #QtrSEnd = cast(right(#finYear,4) as varchar(4))+'-'+cast(month(#QtrSEnd) as Varchar(2))+'-'+Cast(day(#QtrSEnd) as Varchar(2))
end
Create table #tempData
(
Bal numeric(15,2)
)
declare #sql varchar(500),#sql2 varchar(500),#day Varchar(10),#Month varchar(2),#Year varchar(4)
select #day= Day(#QtrSEnd)
select #Month= month(#QtrSEnd)
select #Year= Year(#QtrSEnd)
Create table #temp
( slno int,
glcode Varchar(500),
GlLen int,
ColNO varchar(50),
CellNo varchar(50),
Amount Numeric(15,2)
)
declare #tsql varchar(500)
set #tsql=N'
insert into #temp
select ROW_NUMBER() over(order by glcode) slno,glcode,LEN(Glcode) GlLen,ColNo,CellNo,amount
from BsGl'+#Oflag+'
where glcode <>'''' '
exec(#tsql)
declare #LoopStart int,#loopEnd Int,#glcode varchar(500),#amt numeric(15,0)
select #LoopStart=Min(Slno) from #temp
select #loopEnd=MAX(Slno) from #temp
while (#LoopStart <= #loopEnd)
begin
select #glcode= Glcode from #temp where slno = #LoopStart
set #sql='insert into #tempData select Sum(day'+#day+') from DayBal where AcYear='+#Year+' and acmonth='+#Month+'and GlCode in(SELECT glcode FROM dbo.splitstring(convert(varchar(500),'''+#glcode+''')))'
EXEC(#sql)
update #temp set Amount=(select Bal from #tempData) where slno =#LoopStart
set #LoopStart=#LoopStart+1
Truncate table #tempData
end
set #tsql=''
set #tsql='update BsGl'+#Oflag+' set Amount=0.00 where Glcode ='''' '
EXEC(#tsql)
set #tsql=''
set #tsql='update B set B.amount=isnull(round((Case when A.Amount<0 then A.Amount*(-1) else A.Amount end/1000),0),0) from #temp a inner join BsGl'+#Oflag+' B on a.CellNo=B.CellNo and B.ColNo=A.ColNo'
EXEC(#tsql)
IF(#Oflag='O4')
BEGIN
EXEC [DBO].[CBs_LargeExposer] #QtrSEnd
END
Drop table #temp
End
Not sure if you have tried this already. Try specifying the exact same column name "slno" as in CREATE TABLE statement, in the below two SELECT statements, instead of "Slno".
select #LoopStart=Min(Slno) from #temp
select #loopEnd=MAX(Slno) from #temp
I found the Solution for the error. I created same #temporary table in outer sp as well as in inner sp with different columns. Basically a #temporary table's scope is limited to the session but when you are calling a inner Sp inside a outer sp it will consider a single session.
Outer SP TempTable Declaration
Create table #tempData
(
Bal numeric(15,2)
)
Inner SP TempTable Declaration
CREATE TABLE #tempData(
[ID] int identity(1,1) ,
[Funded] [numeric](15, 2) NOT NULL,
[NonFunded] [numeric](2, 2) NOT NULL,
[Limitsanctioned] [numeric](15, 2) NOT NULL
)
So I changed the #tmpData to #tempData1 in outer Sp it's working fine.

Dynamic SQL Pivot Query with Union All

I have a static pivot query that tracks historical pricing (see below); it is union all of one table of current data, one table of historical data, and one related table.
I would like to convert it to a dynamic SQL pivot query so that I don't manually have to update the column heading dates all of the time, but I am having problems doing so. The data comes out of an accounting system (Microsoft Dynamics) running on SQL Server, and due to system limitations, I am unable to use ansi nulls/ paddings/ warnings and also unable to use quoted identifiers. Is there another way to create a dynamic sql pivot query?
Here is my current query. I want to replace the month-end dates with dynamic sql. I have view access to the data only.
SELECT ACTDESCR AS "ACCT NAME", concat(right(actnumbr_2,2), actnumbr_3) as PLU, [3/31/2015], [2/28/2015], [1/31/2015], [12/31/2015], [11/30/2014], [10/31/2014], [9/30/2014], [8/31/2014], [7/31/2014], [6/30/2014], [5/31/2014], [4/30/2014], [3/31/2014], [2/28/2014], [1/31/2014]
FROM
(SELECT A.ACTDESCR, EOMONTH(DATEFROMPARTS(B.YEAR1,B.PERIODID,1),0) AS DATE1, A.actnumbr_2, a.actnumbr_3, B.PERDBLNC, A.ACTNUMBR_1
FROM TEST.dbo.table1 AS A
LEFT OUTER JOIN TEST.dbo.TABLE2 AS b
ON (a.ACTINDX = b.ACTINDX)
UNION ALL
SELECT A.ACTDESCR, EOMONTH(DATEFROMPARTS(C.YEAR1,C.PERIODID,1),0) AS DATE1, A.actnumbr_2, a.actnumbr_3, C.PERDBLNC, A.ACTNUMBR_1
FROM TEST.dbo.TABLE1 AS A
LEFT OUTER JOIN TEST.dbo.TABLE3 AS C
ON (a.ACTINDX = C.ACTINDX)
) AS ST
PIVOT
(
SUM(PERDBLNC)
FOR DATE1 IN ([3/31/2015], [2/28/2015], [1/31/2015], [12/31/2015], [11/30/2014], [10/31/2014], [9/30/2014], [8/31/2014], [7/31/2014], [6/30/2014], [5/31/2014], [4/30/2014], [3/31/2014], [2/28/2014], [1/31/2014])
) AS PVT
WHERE ACTNUMBR_1 = ?
You can use T-SQL with dynamic SQL for this:
--VARIABLE TO HOLD DATES--
DECLARE #DATES NVARCHAR(500)
--VARIABLE TO HOLD CODE--
DECLARE #SQL NVARCHAR(MAX)
--TEMP TABLE TO FIND DISTINCT DATES--
CREATE #DATES (COLUMNVALS NVARCHAR(10))
--INSERT DISTINCT DATES INTO TEMP TABLE--
INSERT INTO #DATES
SELECT DISTINCT DATE1 FROM (
SELECT EOMONTH(DATEFROMPARTS(YEAR1,PERIODID,1),0) AS DATE1
FROM TEST.DBO.TABLE2
UNION ALL
SELECT EOMONTH(DATEFROMPARTS(YEAR1,PERIODID,1),0) AS DATE1
FROM TEST.DBO.TABLE3)
--CONCAT DATES INTO SELECT LIST--
SET #DATES = COALESCE(#DATES+', ','') + '[' + DATE1 + ']' FROM #DATES
--CREATE THE SELECT STATEMENT--
SELECT #SQL = '
;WITH ST AS (
SELECT A.ACTDESCR, EOMONTH(DATEFROMPARTS(B.YEAR1,B.PERIODID,1),0) AS DATE1, A.ACTNUMBR_2, A.ACTNUMBR_3, B.PERDBLNC, A.ACTNUMBR_1
FROM TEST.DBO.TABLE1 AS A
LEFT OUTER JOIN TEST.DBO.TABLE2 AS B
ON A.ACTINDX = B.ACTINDX
UNION ALL
SELECT A.ACTDESCR, EOMONTH(DATEFROMPARTS(C.YEAR1,C.PERIODID,1),0) AS DATE1, A.ACTNUMBR_2, A.ACTNUMBR_3, C.PERDBLNC, A.ACTNUMBR_1
FROM TEST.DBO.TABLE1 AS A
LEFT OUTER JOIN TEST.DBO.TABLE3 AS C
ON A.ACTINDX = C.ACTINDX)
SELECT ACTDESCR AS "ACCT NAME", CONCAT(RIGHT(ACTNUMBR_2,2), ACTNUMBR_3) AS PLU, '+#DATES+'
FROM ST
PIVOT
(
SUM(PERDBLNC)
FOR DATE1 IN ('+#DATES+')
) AS PVT
WHERE ACTNUMBR_1 = ?'
--PRINT IT TO SEE WHAT IT'S DONE--
PRINT #SQL
--EXECUTE IT--
EXEC (#SQL)

How to solve this variable pass into batch_date?

I want to pass in #batch date into batch_date...But it shows error...The error is
Column 'dbo.tnx_tid_InvCheck_Details.Batch_Date' is invalid in the
select list because it is not contained in either an aggregate
function or the GROUP BY clause.
The InvCheck_Details table has batch_date for each and every part_no. I want to group the part_no so that I can count(tid) and sum(tid_bal) by part_no. What should i do in order to run this script? TQ...
DECLARE #batch_date datetime
SET #batch_date = '2012-10-13 00:00:00.000'
CREATE TABLE #inv_check
(batch_date datetime,part_no varchar(25),Number_of_tid int,Updated_DT int, Tot_Tid_Bal int)
INSERT INTO #inv_check
SELECT batch_date,part_no,COUNT(tid)as Number_of_tid,0,sum(Tid_Bal)
FROM dbo.tnx_tid_InvCheck_Details
where batch_date = #batch_date
Group by part_no
order by part_no
UPDATE #inv_check
SET Updated_DT = isnull(d.Updated_DT,0)
--select i.part_no,i.Number_of_tid, isnull(d.Updated_DT,0)
FROM #inv_check i
LEFT OUTER JOIN
(SELECT part_no, COUNT(LastUpdate_DT)as Updated_DT,
sum(tid_bal) as Tid_bal_sum
FROM dbo.tnx_tid_InvCheck_Details
Where NOT LastUpdate_DT IS NULL
Group by part_no) d on i.part_no=d.part_no
DECLARE #sql int
DECLARE #sql1 int
SELECT #sql1 = count(part_no)
FROM #inv_check
SELECT #sql = count(part_no)
FROM #inv_check
WHERE number_of_tid= Updated_DT
SELECT #sql AS Parts_Counted,#sql1 AS Full_Parts
Drop table #inv_check
Try this
INSERT INTO #inv_check
Select y.batch_date,x.*
From dbo.tnx_tid_InvCheck_Details y
Join(
SELECT part_no,COUNT(tid)as Number_of_tid,0 AS Updated_DT,sum(Tid_Bal) As Tot_Tid_Bal
FROM dbo.tnx_tid_InvCheck_Details
where batch_date = #batch_date
Group by part_no
)x
On x.part_no = y.part_no
order by x.part_no

Resources