The multi-part identifier could not be bound in SQL Server 2012 - sql-server-2012

I am trying to use resource attributes table in IF block. Error is in second if block:
Multi-part identifier 'ra.Start_dt' could not be bound
I have used the alias name i.e. ra, even then I get this error. Can someone help me out with this code?
IF (#toyear - #fromyear = 0)
BEGIN
SET #vacsql = 'SELECT DISTINCT
a.resourceID, r.EnterpriseID, r.FullName,
dbo.fnGetWorkOrdersByResourceID(a.resourceID,' +
CAST(#tomonth AS VARCHAR(2)) + ',' +
CAST(#toyear AS VARCHAR(4)) + ') AS WorkOrder,
dbo.fnGetDomainsByResourceID(a.resourceID,' +
CAST(#tomonth AS VARCHAR(2)) + ',' +
CAST(#toyear AS VARCHAR(4)) + ') AS Domain,
l.Offshore_Ind,
SUM(ISNULL(a.Totals, 0)) AS TOTALHOURS
FROM
[Actuals] AS a
JOIN
[Resources] AS r ON a.ResourceID = r.ResourceID
JOIN
Resource_Attributes AS ra ON r.ResourceID = ra.ResourceID
JOIN
Location_LU AS l ON ra.LocationID = l.LocationID
JOIN
Roll_On_Off AS ro ON r.ResourceID = ro.ResourceID
WHERE
(a.TaskName = ''Leave'')
AND a.CalYear = ' + CAST(#toyear AS VARCHAR(10)) +
' AND CalMonthNum <= ' + CAST(#tomonth AS VARCHAR(10)) +
' AND CalMonthNum >= ' + CAST(#frommonth AS VARCHAR(10)) +
'AND (CONVERT(datetime, ro.End_Dt)) > (CONVERT(datetime, '''+cast(concat(#frommonth,'/01/',#toyear) as varchar(10))+'''))
(CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate))
GROUP BY ra.AttributeID,a.ResourceID,r.EnterpriseID,r.FullName,l.offshore_Ind'
if((CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate)) AND CONVERT(datetime,ra.Start_dt) between (CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,#EndDate)))
BEGIN
INSERT INTO #vacTable EXECUTE sp_executesql #vacsql,
N'#StartDate varchar(25), #EndDate varchar(25)',
#StartDate,
#EndDate;
END

try this!
if (#toyear-#fromyear=0)
BEGIN
Set #vacsql = 'SELECT DISTINCT a.resourceID,r.EnterpriseID,r.FullName, dbo.fnGetWorkOrdersByResourceID(a.resourceID,'+ CAST(#tomonth AS VARCHAR(2))+','+CAST(#toyear AS VARCHAR(4)) +') as WorkOrder,
dbo.fnGetDomainsByResourceID(a.resourceID,'+ CAST(#tomonth AS VARCHAR(2))+','+CAST(#toyear AS VARCHAR(4)) +') as Domain, l.Offshore_Ind,SUM(ISNULL(a.Totals,0)) AS TOTALHOURS
FROM [Actuals] AS a join [Resources] AS r on a.ResourceID=r.ResourceID
join Resource_Attributes as ra on r.ResourceID=ra.ResourceID
join Location_LU as l on ra.LocationID=l.LocationID
join Roll_On_Off as ro on r.ResourceID=ro.ResourceID
WHERE (a.TaskName=''Leave'') AND a.CalYear='+CAST(#toyear as varchar(10))+' AND CalMonthNum <='+CAST(#tomonth as varchar(10))+' AND CalMonthNum >='+CAST(#frommonth as varchar(10))+'
AND (CONVERT(datetime,ro.End_Dt))>(CONVERT(datetime,'''+cast(concat(#frommonth,'/01/',#toyear) as varchar(10))+'''))
(CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate))
GROUP BY ra.AttributeID,a.ResourceID,r.EnterpriseID,r.FullName,l.offshore_Ind'
if exists (select 1 from Resource_Attributes ra where (CONVERT(datetime,ra.Start_dt))<=(CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,ra.End_dt))>=(CONVERT(datetime,#EndDate)) AND CONVERT(datetime,ra.Start_dt) between (CONVERT(datetime,#StartDate)) AND (CONVERT(datetime,#EndDate)))
BEGIN
INSERT INTO #vacTable EXECUTE sp_executesql #vacsql,
N'#StartDate varchar(25), #EndDate varchar(25)',
#StartDate,
#EndDate;
END
END

Related

SQL Pivot Query for Attendance Report

I have below query written for my attendance report. everything works fine except one thing. i have multiple checkin/checkout allowed in a day in my application now when i run my query it returns checkin, checkout, total, checkin checkout total. the result i expect is something like: checkin, checkout, checkin, checkout.... total.
Below is the query:
SELECT EmployeeID, Employee, [2016-09-01],[2016-09-02],[2016-09-05],[2016-09-06],[2016-09-07],[2016-09-08],[2016-09-09] from
(
SELECT src.EmployeeID, isnull(b.EmployeeName,'') +' '+ isnull(b.LastName,'') Employee
,[CheckinDate]
, ISNULL(CAST(c.LeaveDesc as VARCHAR(max)), STUFF((
SELECT ', ' + CAST(ISNULL(CheckinTime,'') AS VARCHAR(5)) + char(10) + CAST(ISNULL(CheckoutTime,'') AS VARCHAR(5)) +
char(10) + CAST(ISNULL(TotalHours,'') AS VARCHAR(5))
FROM EmployeeDetail
WHERE (EmployeeID = src.EmployeeID and CheckinDate = src.CheckinDate)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'')) AS Result
FROM [EmployeeDetail] as src inner join EmployeeMaster b on src.EmployeeID = b.EmployeeID and src.KindergardenID = b.KindergardenID
left outer join leavetype c on src.leaveid = c.leaveid
WHERE src.KindergardenID = 1
GROUP BY src.EmployeeID, isnull(b.EmployeeName,'') +' '+ isnull(b.LastName,''), CheckinDate,LeaveDesc
) x
pivot
(
max(Result)
for CheckinDate in ([2016-09-01],[2016-09-02],[2016-09-05],[2016-09-06],[2016-09-07],[2016-09-08],[2016-09-09])
) p
Any help in changing the query to make it work as expected is appreciated.
Let me know if i was confusing in asking.
SELECT EmployeeID, Employee, ' + #cols + ' from
(
SELECT src.EmployeeID, isnull(b.EmployeeName,'''') +'' ''+ isnull(b.LastName,'''') Employee
,[CheckinDate]
, ISNULL(CAST(c.LeaveDesc as VARCHAR(max)), isnull(left(convert(time,DATEADD(minute,(SUM(DATEDIFF(MINUTE, ''0:00:00'', TotalHours))),0)),5),''N/A'') + char(10) + STUFF((
SELECT '', '' + CAST(ISNULL(CheckinTime,'''') AS VARCHAR(5)) + ''-'' + CAST(ISNULL(CheckoutTime,'''') AS VARCHAR(5)) +
char(10)
FROM EmployeeDetail
WHERE (EmployeeID = src.EmployeeID and CheckinDate = src.CheckinDate)
FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)'')
,1,2,'''')) AS Result
FROM [EmployeeDetail] as src inner join EmployeeMaster b on src.EmployeeID = b.EmployeeID and src.KindergardenID = b.KindergardenID
left outer join leavetype c on src.leaveid = c.leaveid
WHERE src.KindergardenID = ' + CAST(#kindergardenid as varchar(max)) + '
GROUP BY src.EmployeeID, isnull(b.EmployeeName,'''') +'' ''+ isnull(b.LastName,''''), CheckinDate,LeaveDesc
) x
pivot
(
max(Result)
for CheckinDate in (' + #cols + ')
) p

Stored procedure passing like statement in case

ALTER PROCEDURE [dbo].[ViewSo]
#Dt1 as datetime,
#Dt2 as datetime,
#CusName as nvarchar,
#so_no as nvarchar
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM
(SELECT
0 as stat,
m.id, f.id as fg_id, f.fg_des, m.so_no,
Replace(CONVERT(NVARCHAR, CAST(m.so_date AS DATE) , 106),' ','-') AS so_date,
Convert(NVARCHAR,CAST(m.so_date AS DATE),101) AS so_date1,
m.cus_name, m.so_cus_id, m.doc_no, m.sale_person, m.so_rem,
f.fg_des AS eXP1, f.fg_qty,
CONVERT(VARCHAR(10), CAST(f.req_date AS DATE), 101) AS req_date,
CASE
WHEN COALESCE (q.tot_req_qty, 0) < f.fg_qty
THEN 'Not Updated'
ELSE 'Updated'
END AS req_qty_stat,
'SO No :' + CONVERT(varchar(15), m.so_no) + '/SO Date :' + CONVERT(varchar(15), REPLACE(CONVERT(NVARCHAR, CAST(m.so_date AS DATE), 106), ' ', '-')) + '/Cus Name :' + CONVERT(varchar(15), m.cus_name) + '/Sales Prsn :' + CONVERT(varchar(15), m.sale_person) AS filter ,
f.fg_no,m.so_stat,
m.del_flag, m.st_stat, m.st_rem
FROM
so_mas AS m
INNER JOIN
so_fg AS f ON m.id = f.so_id
LEFT OUTER JOIN
(SELECT
fg_id, SUM(req_qty) AS tot_req_qty
FROM
fg_qty
WHERE
(del_flag = 0)
GROUP BY fg_id) AS q ON q.fg_id = f.id
WHERE
m.del_flag = 0) AS S
WHERE
CONVERT(datetime, s.so_date) BETWEEN #Dt1 AND #Dt2
AND S.cus_name LIKE
CASE WHEN #CusName = '' THEN S.cus_name
ELSE +'%' + #CusName + '%'
END
ORDER BY
s.so_date;
END
This is my stored procedure passing like statement in case. If run as query it works fine. If I used as stored produce leads to wrong result.
Please help me to solve.
Replace this part of WHERE
AND S.cus_name LIKE
CASE WHEN #CusName = '' THEN S.cus_name
ELSE +'%' + #CusName + '%'
END
With
AND S.cus_name LIKE
CASE WHEN #CusName = '' THEN S.cus_name
ELSE '%' + #CusName + '%'
END

Conversion failed when converting the nvarchar value '29449,29446,29450,29534' to data type int

I am create a stored procedure in SQL and I get the following error when I execute the query:
Conversion failed when converting the nvarchar value '11021,78542,12456,24521' to data type int.
Any idea why?
SELECT
A.Art_ID, A.Title
FROM
Art A
INNER JOIN
Iss I ON A.Iss_ID = I.Iss_ID
INNER JOIN
Sections S ON A.Section_ID = S.Section_ID
INNER JOIN
iPadSec IPS ON A.Sec_ID = IPS.Sec_ID
WHERE
A.Art_ID IN (SELECT CAST(Art_IDs AS int) /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68)
AND I.Iss > dateadd(month, -13, getdate())
AND A.Active = 1
AND IPS.Active = 1
AND A.PDate <= getdate()
ORDER BY
PDate DESC, Art_ID DESC;
You cannot do what you want using in. First, it is a really bad idea to store ids in lists in strings. You should be using a junction table.
That said, sometimes this is necessary. You can rewrite this line of code as:
EXISTS (SELECT 1 /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68 AND
',' + Art_IDs + ',' LIKE '%,' + cast(A.Art_ID as varchar(255)) + ',%'
)
However, the performance would generally be on the lousy side and there is little prospect of speeding this up without fixing the data structure. Use a junction table instead of a string to store lists.
Adding this line works for me.
declare #ids varchar(1000)
select #ids = art_ids from book_art where sub_id = #Sub_ID
EXECUTE ( 'SELECT A.Art_ID, A.Title'
+ ' FROM Art A'
+ ' INNER JOIN Iss I ON A.Iss_ID = I.Iss_ID'
+ ' INNER JOIN Sections S ON A.Section_ID = S.Section_ID'
+ ' INNER JOIN iPadSec IPS ON A.Sec_ID = IPS.Sec_ID'
+ ' WHERE A.Art_ID IN (' + #ids + ')'
+ ' AND I.Iss > dateadd(month, -13, getdate())'
+ ' AND A.Active = 1'
+ ' AND IPS.Active = 1'
+ ' AND A.PDate <= getdate()'
+ ' ORDER BY PDate DESC,'
+ ' Art_ID DESC;'
)
END
Thank you all for your help :)

SQL Dynamic Pivot

I have written a dynamic SQL Pivot Query that returns a Quantity per day, the number of columns returned are dynamic based on the number of days between the opening parameters. The issue I am having is that the Columns are not in DateOrder, I am guessing I need some form or Order By to fix this, does anyone have any ideas where I would need to put it in?
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
--declare and set variables
DECLARE #v_Columns VARCHAR(MAX)
,#v_StartDate DATETIME = GETDATE() - 10
,#v_EndDate DATETIME = GETDATE()
,#v_Query VARCHAR(max)
--select results
SELECT #v_Columns = Coalesce(#v_Columns, '[') + convert(VARCHAR, cast(DateCreated AS DATE), 111) + '],['
FROM (
SELECT DISTINCT cast(DateCreated AS DATE) AS DateCreated
FROM TransactionOriginTracking
) tot
WHERE tot.DateCreated BETWEEN #v_StartDate
AND #v_EndDate
SET #v_Columns = SUBSTRING(#v_Columns, 1, Len(#v_Columns) - 2)
SET #v_Query = 'select
*
from
(
SELECT
cast(Tracking.DateCreated as date) as [Date],
th.TotalQuantity [Quantity]
FROM
TransactionHeader th
Inner JOin TransactionOriginTracking as Tracking on Tracking.TransactionHeaderId = th.Id
and Tracking.WorkflowStageId = 9
Inner Join CompanyDivision on CompanyDivision.Id = th.CompanyDivisionId
WHERE
Tracking.DateCreated between ''' + CONVERT(VARCHAR(50), #v_StartDate, 111) + ''' AND ''' + CONVERT(VARCHAR(50), #v_EndDate, 111) + '''
) as src
Pivot
(
SUM(src.Quantity)
For src.Date IN (' + #v_Columns + ')
) as PivotView'
EXEC (#v_Query)
When you build up your column list, sort by date:
--select results
SELECT
#v_Columns = Coalesce(#v_Columns, '[') + convert(VARCHAR, cast(DateCreated AS DATE), 111) + '],['
FROM
(SELECT DISTINCT
CAST(DateCreated AS DATE) AS DateCreated
FROM
TransactionOriginTracking) tot
WHERE
tot.DateCreated BETWEEN #v_StartDate AND #v_EndDate
ORDER BY
tot.DateCreated

Using Group By Clause in Stored procedure

I have a storedprocedure in which iam getting InvoiceValue as one field.I have different invoice values corresponding to 1 fileid.I want to get the sum of invoice values corresponding to each fileid.How can i use group by here?
here is my stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[rptGGM]
(
#FromDate varchar(50),
#ToDate varchar(50),
#PartyID int,
#WID int
)
As
DECLARE #WhereStr VarChar(800)
SET #FromDate = LTRIM(RTRIM(#FromDate))
SET #ToDate = LTRIM(RTRIM(#ToDate))
SET #WhereStr =
CASE #WID
WHEN 23 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+'''))'
WHEN 7 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 6 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 11 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 12 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
END
BEGIN
exec
('SELECT
A.FileNumber As [File_No],
H.IDFNumber as [IDF No],
H.IDFRegNo as [TZDAR],
F.POString As [PO_Numbers],
B.PartyName As [Exporter Name],
F.SIString As [Supplier Invoices],
C.CargoDesc As [Cargo_Description],
dbo.PackCntDetails(A.FileID) As [Pk/Cnt_Details],
D.VesselName As [Vessel Name],
D.VoyageNo As [Voyage No],
L.Amount As [Invoice Value],
convert(varchar, Dbo.ActualDate(A.ETA), 103) + '' '' + convert(varchar, Dbo.ActualDate(A.ETA), 108) As ETA,
convert(varchar,Dbo.ActualDate(D.ATASea),103) + '' '' + convert(varchar, Dbo.ActualDate(D.ATASea), 108) As ATA,
convert(varchar,Dbo.ActualDate(H.PCVRIssuedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.PCVRIssuedDate), 108) as [PCVR Issued Date],
convert(varchar,Dbo.ActualDate(V.VATRelDate),103) + '' '' + convert(varchar, Dbo.ActualDate(V.VATRelDate), 108) as [VR Requested],
convert(varchar,Dbo.ActualDate(V.OriginalRecdDate),103) + '' '' + convert(varchar, Dbo.ActualDate(V.OriginalRecdDate), 108) as [VR Granted],
convert(varchar,Dbo.ActualDate(H.SBECVRAppReturnedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.SBECVRAppReturnedDate), 108) as [SBE _VR App. ReturnedDate],
convert(varchar,Dbo.ActualDate(H.SBECVRIssuedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.SBECVRIssuedDate), 108) as [SBE_CVR IssuedDate],
convert(varchar,Dbo.ActualDate(I.CDFLodgedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.CDFLodgedDate), 108) as [CDF LodgedDate],
convert(varchar,dbo.ActualDate(I.AssessmentPaidDate), 103) + '' '' + convert(varchar,dbo.ActualDate(I.AssessmentPaidDate),108) As [DutyPaidDate],
convert(varchar,Dbo.ActualDate(I.EntryLodgedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.EntryLodgedDate), 108) as [Entry LodgedDate],
convert(varchar,Dbo.ActualDate(I.EntryPassedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.EntryPassedDate), 108) as [Custom Released],
[Actual Days from ATA to CR]=DATEDIFF(dd, Dbo.ActualDate(D.ATASea),Dbo.ActualDate(I.EntryPassedDate)),
convert(varchar,Dbo.ActualDate(K.ShippingLineReleaseDate),103) + '' '' + convert(varchar, Dbo.ActualDate(K.ShippingLineReleaseDate),108) as [ShippingLine ReleaseDate],
convert(varchar,Dbo.ActualDate(K.PortInvoicePaidDate),103) + '' '' + convert(varchar, Dbo.ActualDate(K.PortInvoicePaidDate),108) as [Port_Charges Paid_Date],
convert(varchar,Dbo.ActualDate(K.RemPortYardDateSea),103) + '' '' + convert(varchar, Dbo.ActualDate(K.RemPortYardDateSea),108) as [Rem_Sea_Port to Yard_Date],
[Actual Days From CR to RFD Dar]=DATEDIFF(dd,Dbo.ActualDate(I.EntryPassedDate), Dbo.ActualDate(K.RemPortYardDateSea)),
[Total No: of Days(ATA-RFD)]=DATEDIFF(dd,Dbo.ActualDate(D.ATASea), Dbo.ActualDate(K.RemPortYardDateSea)),
A.Remarks As [File Status]
FROM
FileMain A
INNER JOIN Party G ON G.PartyID = A.PartyID
LEFT JOIN Party B ON B.PartyID = A.ExporterID
LEFT JOIN Cargo C ON C.FileID = A.FileID
LEFT JOIN FileSea D ON D.FileID = A.FileID
LEFT JOIN SIPOString F ON F.FileID=A.FileID
LEFT JOIN IDFMain H ON H.FileID=A.FileID
LEFT JOIN Customs I ON I.FileID=A.FileID
LEFT JOIN VATRelief V ON V.FileID=A.FileID
LEFT JOIN PortAirPortOperation K ON K.FileID=A.FileID
LEFT JOIN Invoice L ON L.FileID=A.FileID and L.Incoterm=''CIF''' +#WhereStr)
END
The quickest implementation here would be to not use a GROUP BY. I would instead use a SubQuery within your SELECT to perform the SUM of the invoices.
Remove the LEFT JOIN to Invoice and then relace the L.Amount line in the SELECT with a SubQuery as follows
(SELECT SUM(Amount) FROM Invoice WHERE Invoice.FileID = A.FileID and Invoice.Incoterm = 'CIF') [Invoice Value]
If you wish to use a GROUP BY to perform the SUM then you either need to GROUP on all your other columns you SELECT, or perform the GROUP by within a VIEW (probably nested).