Why SSIS Package Succeeds but Flat File Destinations Write Zero Rows? - sql-server

I have a very straightforward, in my opinion, SSIS package comprised of 8 Data Flow Tasks. Each task is composed of an OLEDB Source that calls a query stored in a variable and a Flat File Destination that writes the contents of the query to a pipe-delimited text file on the network.
The original version of the package worked but the package needed modification to add new fields to the flat files. I deleted all Flat File Destinations and corresponding connection managers and created new ones. The queries have been tested independently and they return data. The OLEDB SQL Server provider uses Windows Authentication.
The package is executed inside Visual Studio 2019 and runs successfully, but each of the 8 resulting flat files are empty except for the column headers.
I've updated my Visual Studio 2019 installation to use the Integration Services extension 4.3 (latest). I copied the following query from one of my variables to SSMS and receive results:
Declare #PrevYearSvcStartDate date = '1/1/2021', #PrevYearSvcEndDate
date = '12/31/2021',
#PrevYearPaidStartDate date = '1/1/2021', #PrevYearPaidEndDate date =
'12/31/2021'
SELECT Distinct
mmpi.FIRSTNM AS 'Claimant First Name',-- Claimant First Name
mmpi.LASTNM AS 'Claimant Last Name',-- Claimant Last Name
ISNULL(mmpi.MI, '') AS 'Claimant Middle Initial',-- Claimant Middle Initial
mc.MEMBID AS 'Claimant Identification Number',-- Claimant Identification Number (to include the member number & suffix if applicable)
Format(mmpi.BIRTH, 'MM/dd/yyyy') AS 'Claimant Date of Birth ', -- Claimant Date of Birth
Format(mhp.OPFROMDT, 'MM/dd/yyyy') AS 'Claimant Effective Date of coverage',-- Claimant Effective Date of coverage
CASE
when cm.HPCode = 'BB' then 'Bueno Beverage'
when cm.HPCode = 'BC' then 'Blue Cross'
when cm.HPCode = 'BS' then 'Blue Shield'
when cm.HPCode = 'HN' then 'Health Net'
when cm.HPCode = 'HU' then 'Humana'
when cm.HPCode = 'KD' then 'Kaweah Health'
when cm.HPCode = 'RN' then 'R&N Market'
when cm.HPCode = 'UH' then 'United Healthcare'
end AS 'Health Plan name', -- Health Plan name
'Medical Group' AS 'IPA Affiliation', -- IPA Affiliation (e.g. Regal, Lakeside, etc)
cm.OPT as 'Benefit Option Code', CASE
WHEN cm.HPCODE IN ('BC', 'BS', 'HN', 'UH')
THEN 'COMMERCIAL'
ELSE 'MEDICARE'
END AS 'Line of Business', -- Line of Business (e.g. Commercial,
Medicare, Medicaid)
cm.CLAIMNO AS 'Claim number', -- Claim number
cd.[SEQUENCE] AS 'Claim Sequence Number', -- Claim Sequence Number
COALESCE(NULLIF(pmpi.FIRSTNAME,''),'')
+COALESCE(' ' + NULLIF(pmpi.LASTNAME,''),'') AS 'Provider Name',
IsNull(PC.PROVID, '') AS 'Provider ID Number',
IsNull(PA.ZIP, '') AS 'Provider Zip',
IsNull(cc3.Code, '') AS 'Provider Specialty Code',
IsNull(pmpi.SUFFIX, '') AS 'Provider Degree',
ISNULL(cc1.Code, '') AS 'Place of Service ', -- Place of Service
Format(cd.FROMDATESVC, 'MM/dd/yyyy') AS 'Date of Service, from date', --
Date of Service, from date
Format(cd.TODATESVC, 'MM/dd/yyyy') AS 'Date of Service, through date', -
- Date of Service, through date
cd.QTY AS 'Procedure quantity', -- Procedure quantity (units)
DATEDIFF(DAY, cd.FROMDATESVC, cd.TODATESVC) AS 'Length of Stay', --
Length of Stay (days)
LTrim(Rtrim(ISNULL(cd.HSERVICECD,''))) AS 'Revenue Codes', -- Type of
Service (UB-92 Revenue Codes)
LTrim(RTrim(ISNULL(cd.PROCCODE, ''))) AS 'Procedure Codes', -- Type of
Service (CPT Procedure Codes, HCPCS codes, when applicable)
ISNULL(cd.PROCDESC, '') AS 'Type of Service Description', -- Type of
Service Description
ISNULL(cd.Modif, '') as 'Modifier',
ISNULL(cm.DRGCode, '') AS 'DRG Code', -- DRG Code
CD.DIAGCODE AS 'Diagnosis codes', -- Diagnosis codes
D.DIAGDESC AS 'Diagnosis codes description', -- Diagnosis codes
description
cd.BILLED AS 'Billed/charged amount', -- Billed/charged amount
cd.CONTRVAL AS 'Contracted amount', -- Contracted amount
cd.ALLOWED AS 'Allowed Amount', --allowed Amount
cd.NET AS 'Paid amount', -- Paid amount
Format(cd.DATEPAID, 'MM/dd/yyyy') AS 'Date paid', -- Date paid
ISNULL(cd.CHECKNO, '') AS 'Check Number',-- Check Number
cm.NET AS 'Covered expense amount basis', -- Covered expense amount
basis* (e.g. DRG, outliers, per diem, global rate, fee for service
discount)
CASE
WHEN BPHP.LOB_NETWORK = 1
THEN 'IN'
When BPHP.LOB_NETWORK = 0
Then 'OUT'
ELSE ''
END AS 'In/Out of network indicator',-- In/Out of network indicator
ISNULL(cd.ADJCODE,'') AS 'Claim Line Adjustment code', -- Claim Line
Adjustment code
ISNULL(replace(Replace(cc.[Description],char(10),''),Char(13),''),'') AS
'Claim Line Adjustment reason', -- Claim Line Adjustment reason
CASE
when BPHP.LOB_NETWORK = 1 then 'CP'
when BPHP.LOB_NETWORK = 0 then 'NCP' ELSE ''
END AS 'Contracted/Non-contracted provider indicator', --
Contracted/Non-contracted provider indicator
cd.Net
FROM
CLAIM_DETAILS cd
INNER JOIN(
Select ClaimNo, Memb_KeyID, Company_ID, HPCode, OPT, PlaceSvc, Status,
Net, Vendor, Prov_KEYID, DRGCode
from Claim_HMasters
Union
Select ClaimNo, Memb_KeyID,Company_ID, HPCode, OPT, PlaceSvc, Status,
Net, Vendor, Prov_KEYID, '' as DRGCode
from Claim_PMasters
) cm ON cd.CLAIMNO = cm.CLAIMNO and cd.Company_ID = cm.Company_ID
inner join Common_Codes cc1 on cm.PlaceSvc = cc1.Common_Code_ID
and cm.Company_ID = cc1.Environment_ID
and cc1.Common_Category_ID = 59
INNER JOIN MEMB_COMPANY mc on mc.MEMB_KEYID = cm.MEMB_KEYID
and mc.HPCODE = cm.HPCODE
and mc.COMPANY_ID = cm.Company_ID
INNER JOIN MEMB_MPI mmpi on mmpi.MEMB_MPI_NO = mc.MEMB_MPI_NO
and mc.Company_ID = mmpi.Environment_ID
LEFT JOIN MEMB_HPHISTS mhp ON mc.MEMB_KEYID = mhp.MEMB_KEYID
and cd.Company_ID = mhp.Company_ID
and cd.FROMDATESVC BETWEEN OPFROMDT and ISNULL(OPTHRUDT,getdate())
INNER JOIN (
Select dx.ClaimNo, dx.Company_ID, cdc.Description as DiagDesc
from Claim_Diags dx
inner join Claim_Details det on dx.ClaimNo = det.ClaimNo and
dx.Company_ID = det.Company_ID
inner join Common_Diagnostic_Codes cdc on dx.DIAG =
cdc.Common_Diagnostic_Code_ID
and dx.Company_ID = cdc.Environment_ID
where DiagRefNo = '1'
and cdc.Environment_ID = 'MSO'
and det.ToDateSvc between #PrevYearSvcStartDate and
#PrevYearSvcEndDate
and det.DatePaid between #PrevYearPaidStartDate and
#PrevYearPaidEndDate
) D on CD.CLAIMNO = D.CLAIMNO and cd.Company_ID = d.Company_ID
LEFT JOIN [BM_PROV_HP_LINEOFBUSS] BPHP ON BPHP.PROV_KEYID =
cm.PROV_KEYID
and BPHP.HPCODE = CM.HPCODE
AND IIF(LTRIM(RTRIM(cm.OPT)) IN
('651244499','651244400','592314503','592314502','592314511', '592314512','592314514','592314501','592314508','592314507','592314506','592314509','592314599','592314599','625221160','625221164','625221165'),
'PPO','HMO') =
BPHP.LOB
AND BPHP.VENDOR = CM.VENDOR
and BPHP.Company_ID = cm.Company_ID
INNER JOIN PROV_COMPANY pc on pc.PROV_KEYID = cm.PROV_KEYID
and cm.Company_ID = pc.Company_ID
INNER JOIN PROV_MPI pmpi on pmpi.PROV_MPI_NO = pc.PROV_MPI_NO
and pc.Company_ID = pmpi.Environment_ID
LEFT JOIN PROV_ADDINFO pa ON cm.PROV_KEYID = pa.PROV_KEYID
and cm.Company_ID = pa.Company_ID
and pa.IsDefault=1
left JOIN Common_Codes cc ON CD.ADJCODE_ID = CC.Common_Code_ID
and cd.Company_ID = cc.Environment_ID
AND CC.Common_Category_ID = 57
Inner Join PROV_SPECINFO PS on cm.PROV_KEYID = PS.PROV_KEYID
and cm.Company_ID = ps.Company_ID
And PS.[SEQUENCE] = '1'
left join Common_Codes cc3 on ps.SPec_Code = cc3.Common_Code_ID
and ps.Company_ID = cc3.Environment_ID
and cc3.Common_Category_ID = 85
WHERE
cm.HPCODE IN ('BS', 'BC', 'HN', 'UH')
and CD.ToDateSvc between #PrevYearSvcStartDate and #PrevYearSvcEndDate
and CD.DatePaid between #PrevYearPaidStartDate and #PrevYearPaidEndDate
AND cm.STATUS = '47'
AND substring(cm.ClaimNo,9,1) = '8'
What should I check to ensure the package produces data?

Related

SQL Query to group by time and roll up and concatenate string values

I am trying to get a particular format from a group of times and days between two tables.
Database:
MeetingTime table has a relationship from MeetingTime.DayOfWeekId (foreign key) to table DayOfWeek.Id (Primary Key). Example Query:
select t.ClassId, d.Name, t.StartTime, t.EndTime
From MeetingTime t
Inner Join DaysOfWeek d on d.Id = t.DayOfWeekId
Where t.classId = 8
Results:
My desired results for this set of data would be one row, because the start and end times are the same.
09:00-15:35 M/T/W/Th/F
NOTE, the start and end time above, can be separate columns above, the main goal is display the days of the week for each grouped time.
The monkey wrench is that the times can be completely different or the same. For example this data set:
I would want displayed in 2 rows:
07:35-14:15 M/T/W
08:00-14:15 Th/F
And finally, this dataset where all times are different:
Would display in 5 rows:
13:48-14:48 M
15:48-16:48 T
05:49-23:53 W
14:49-16:49 Th
13:49-16:49 F
I haven't had much success with grouping the times. I did figure out how to concatenate the days of the week rolling the days up into one column using the 'Stuff' Operator, but didn't get anywhere with the grouping of the start and end time coupled with this yet.
Concatenating and rolling up days:
STUFF((SELECT '/ ' +
(CASE
WHEN d.[Name] = 'Thursday' THEN SUBSTRING(d.[Name], 1, 2)
WHEN d.[Name] = 'Sunday' THEN 'U'
WHEN d.[Name] != '' THEN SUBSTRING(d.[Name], 1, 1)
ELSE NULL
END)
FROM MeetingTime m
Inner Join [DayOfWeek] d on d.Id = m.DayOfWeekId
Where m.ClassId = class.Id
FOR XML PATH('')), 1, 1, '') [ClassSchedule]
I'm also not opposed to just returning the rows and handling the data manipulation in C# code, but wanted to see if SQL could handle it.
I was able to get this working. Here is the query:
select
t.ClassId,
t.StartTime,
t.EndTime,
STUFF((SELECT '/' + (CASE
WHEN w.[Name] = 'Thursday' THEN SUBSTRING(w.[Name], 1, 2)
WHEN w.[Name] = 'Sunday' THEN 'U'
WHEN w.[Name] != '' THEN SUBSTRING(w.[Name], 1, 1)
ELSE NULL
END)
From MeetingTime s
Inner Join DayOfWeek w on w.Id = s.DayOfWeekId
Where s.classId = 7 and s.DayOfWeekId > 0
and s.StartTime = t.StartTime
and s.EndTime = t.EndTime
FOR XML PATH('')), 1, 1, '') [ClassSchedule]
From MeetingTime t
Inner Join DayOfWeek d on d.Id = t.DayOfWeekId
Where t.classId = 7 and t.DayOfWeekId > 0
Group by t.StartTime, t.EndTime, t.ClassId
Obviously hardcoded Id you would want to create a variable.
Results where the start and end time are all the same:
Some times the same and some different:
Some times the same and some different with days not in order:
Times all different:
Times with only Mon/Wed/Fri.
I feel pretty good about this, except I'd like to fix the order of the above result image where all times are different and the days are not in chronological order.

How to return T-SQL query with column names as first row

I'm writing a SSIS package to output data from a SQL Server 2012 database to a .CSV file for a client. The requirement is that the first row be the column names. Below is the query I've written for the Source in the Data Flow Task. The problem is, it always returns the column names as the LAST row, not the first. Why? How do I achieve this?
DECLARE #Today AS DateTime= GETDATE()
DECLARE #NextPayrollDate AS DateTime
EXEC mobile.getNextPayrollDate #Today, #NextPayrollDate OUTPUT
;WITH LatestEligible (EmployeeID, LatestBillVerified) AS
(
SELECT
EmployeeID, MAX(DateBillVerified) AS LatestBillVerified
FROM
Inv_DataReimbursement
GROUP BY
EmployeeID
)
SELECT
'Edit Set' AS 'Edit Set',
'Employee No.' AS 'Employee No.'
FROM
LatestEligible
UNION
SELECT
NULL AS 'Edit Set',
d.EmployeeID AS 'Employee No.'
FROM
LatestEligible d
INNER JOIN
Employee e ON d.EmployeeID = e.EmployeeID
INNER JOIN
Inv_DataReimbursement dr ON d.EmployeeID = dr.EmployeeID
AND d.LatestBillVerified = dr.DateBillVerified
WHERE
(dr.MonthlyServiceEligible = 'true'
OR (dr.MonthlyServiceEligible = 'false'
AND e.DateEnd IS NOT NULL
AND e.DateEnd > #NextPayrollDate))
AND dr.ActualAmount > 0
How do I achieve this?
Don't do it through SQL.
Just tick the Column names in the first data row box in the Flat File Connection Manager and leave the original query untouched.
The column headers will then be added automatically without you needing to union this additional metadata (and potentially cast everything as a string on the SQL side).
You could try UNION ALL:
SELECT
'Edit Set' AS 'Edit Set', 'Employee No.' AS 'Employee No.'
FROM LatestEligible
UNION ALL
SELECT DISTINCT
NULL AS 'Edit Set',
d.EmployeeID AS 'Employee No.'
FROM LatestEligible d
INNER JOIN Employee e
ON d.EmployeeID = e.EmployeeID
INNER JOIN Inv_DataReimbursement dr
ON d.EmployeeID = dr.EmployeeID AND d.LatestBillVerified =
dr.DateBillVerified
WHERE (dr.MonthlyServiceEligible = 'true'
OR (dr.MonthlyServiceEligible = 'false' AND e.DateEnd IS NOT NULL AND
e.DateEnd > #NextPayrollDate))
AND dr.ActualAmount > 0

Dynamic table creation SQLSever

I have several tables in SQL sever worth of Employee data including ID's and clock in times. I need to create a report to show clocking times for each day for each employee. i have done this with the below code. However as the clock ins are only recorded if there is an entry i need to show working days where there are no records for a clock in for employees. I've thought about making a table of working days in 2019/2020 including data each employee on each day and using this to join however the table would need continual updating when somebody new starts.
Is there any way the table can update itself with employee numbers and copy working days?
Any help would be appreciated
Thanks
select distinct cast(a.DET_NUMBER as varchar) as 'Frontier ID',
e.CDN_CARD_ID,
CONCAT (a.DET_G1_NAME1, ' ', a.DET_SURNAME) as 'Name',
c.POS_TITLE as 'Position',
c.POS_L3_CD as 'Department',
c.POS_L4_CD as 'Department 2',
cast(a.DET_DATE_JND as date) as 'Start Date',
cast(b.TER_DATE as date) as 'Leaving Date',
CONCAT (d.DET_G1_NAME1, ' ', d.DET_SURNAME) as 'Team Manager',
f.CLO_DATE2,
min(CLO_TIME2) over (partition by f.CLO_DATE2, e.CDN_CARD_ID) as earliest_time,
max(CLO_TIME2) over (partition by f.CLO_DATE2, e.CDN_CARD_ID) as latiest_time
from EMDET a
left outer join EMTER b on a.DET_NUMBER = b.DET_NUMBER
left outer join EMPOS c on a.DET_NUMBER = c.DET_NUMBER
left outer join EMDET d on c.POS_MANEMPNO = d.DET_NUMBER
left outer join TACDN e on a.DET_NUMBER = e.DET_NUMBER
left outer join TACLO f on e.CDN_CARD_ID = f.CLO_CARD_NO
Where (b.TER_DATE is null or c.POS_END>=GETDATE())
and c.POS_TITLE is not null
and (c.POS_END<=Cast('1992-01-01' as datetime) or c.POS_END>=GETDATE())
and f.CLO_DATE >='2019-01-01'
order by [Team Manager] asc,
e.CDN_CARD_ID asc,
f.CLO_DATE2 asc
You can generate a calendar with a CTE
DECLARE #Start DATE = '2018-1-1', #End DATE = GETDATE()
;WITH
dates AS
(
SELECT thedate = #Start
UNION ALL
SELECT dateadd(day,1,dates.thedate)
FROM dates
WHERE dateadd(day,1,dates.thedate) <= #End
)
SELECT *
FROM dates c
OPTION (maxrecursion 0);
Then filter to exclude non-working days (weekens: direct in yourquery, holidays, vacations, permits, etc from other table)
Left join with your actual query

How to use the current select column value in a column sub select in SQL

I have a query that for each row, adds a comma seperated string to one column using a sub query. So for example, a work order may be attached to many parts. I do my regular select, but use the SQL function 'STUFF' to build the 'Parts column. That way in the results, the arts column has multiple entries. So i do i do the sub query for the column i use 'STUFF" on to get all parts using the main column id of the base query? This is a little weird for me to explain but this snippet will help you understand what i am trying to accomplish:
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET FMTONLY OFF;
IF OBJECT_ID('tempdb..#TEMP_KikusuiRpt') IS NOT NULL DROP TABLE #TEMP_KikusuiRpt
-- Get the current date to work on if they do not send in date params. Meaning it is automated run --
-- if hey do send in date ranges, then it is manual run
IF NULLIF(#StartDate, '') IS NULL
BEGIN
-- Set start date param to the first day of the current month
SET #StartDate = DATEADD(mm, DATEDIFF(mm,0,GETDATE()), 0)
END
IF NULLIF(#EndDate, '') IS NULL
BEGIN
-- Set end day to the last day what ever that may be of the current month.
SET #EndDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
END
SELECT
manufacturer.mfrname AS Manufacturer,
model.modelnumber AS BaseModelNumber,
control.controlserialnumber AS Serial,
Customer.CustCompany,
Control.ControlDateAdded as Received,
Control.ControlCalDate as 'Completed (Cal Date)',
WorkOrder.WorkOrderID as woid,
Receiver.ReceiverID,
WorkOrderComments.CommentRcvr as 'Receiver Comments',
WorkOrderCOmments.CommentRpt as 'Report Comments',
ISNULL(STUFF((SELECT ', ' + PartID
FROM WorkOrderPart WOP
INNER JOIN WorkORder WO ON WOP.WorkOrderID = WO.WorkOrderID
INNER JOIN Model ON Model.ModelID = WO.ModelID
WHERE WO.MfrCode IN (SELECT MfrCode FROM Manufacturer where MfrName LIKE '%Kikusui%')
--
-- Right here i need somehow to do this
--
-- the workorder on the stuff query needs to be attached to the base select work order row instance, or else i get all parts in each row not just for the work order
where wo.WorkOrderID = WOID
FOR XML PATH('')
), 1, 1, ''), 'NA') AS Parts
INTO #TEMP_KikusuiRpt
FROM WorkOrder
INNER JOIN Control ON WorkOrder.ControlNumber = Control.ControlNumber
INNER JOIN model ON control.modelid = model.modelid
INNER JOIN manufacturer on model.mfrcode = manufacturer.mfrcode
INNER JOIN WorkOrderComments ON WorkOrderComments.WorkOrderID = WorkOrder.WorkOrderID
INNER JOIN Receiver ON Receiver.ReceiverID = WorkOrder.ReceiverID
INNER JOIN Customer ON Customer.CustID = WorkOrder.CustID
WHERE Manufacturer.MfrName LIKE '%Kikusui%'
AND #StartDate > WorkOrder.DateReceived
AND #EndDate < WorkOrder.DateCompleted
SELECT * FROM #TEMP_KikusuiRpt
DROP TABLE #TEMP_KikusuiRpt
So hopefully i have explained this clearly enough. Is there a way to handle this? The reason being that my Parts column is populated, but not filtered enough to the model that is returned.
You just need to alias your outer and inner model table references. Here's what the main select would look like:
SELECT
manufacturer.mfrname AS Manufacturer,
m1.modelnumber AS BaseModelNumber,
control.controlserialnumber AS Serial,
Customer.CustCompany,
Control.ControlDateAdded as Received,
Control.ControlCalDate as 'Completed (Cal Date)',
WorkOrder.WorkOrderID as woid,
Receiver.ReceiverID,
WorkOrderComments.CommentRcvr as 'Receiver Comments',
WorkOrderCOmments.CommentRpt as 'Report Comments',
ISNULL(STUFF((SELECT ', ' + PartID
FROM WorkOrderPart WOP
INNER JOIN WorkORder WO ON WOP.WorkOrderID = WO.WorkOrderID
INNER JOIN Model m2 ON m2.ModelID = WO.ModelID
WHERE WO.MfrCode IN (SELECT MfrCode FROM Manufacturer where MfrName LIKE '%Kikusui%')
AND m1.modelnumber = m2.modelnumber
FOR XML PATH('')
), 1, 1, ''), 'NA') AS Parts
INTO #TEMP_KikusuiRpt
FROM WorkOrder
INNER JOIN Control ON WorkOrder.ControlNumber = Control.ControlNumber
INNER JOIN model m1 ON control.modelid = m1.modelid
INNER JOIN manufacturer on m1.mfrcode = manufacturer.mfrcode
INNER JOIN WorkOrderComments ON WorkOrderComments.WorkOrderID = WorkOrder.WorkOrderID
INNER JOIN Receiver ON Receiver.ReceiverID = WorkOrder.ReceiverID
INNER JOIN Customer ON Customer.CustID = WorkOrder.CustID
WHERE Manufacturer.MfrName LIKE '%Kikusui%'
AND #StartDate > WorkOrder.DateReceived
AND #EndDate < WorkOrder.DateCompleted

SQL Query generating this error -Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

I have a SQL query Question, I am trying to nest two separate queries which run perfectly fine individually.
The first query is
Select DISTINCT Leads.EmailAddress,ClientCustomFields.CommonName , LeadSources.Name, CONVERT(VARCHAR(10), leads.LeadStatusDate,101) AS [MM/DD/YYYY],Leads.Age,Leads.State, Leads.ProgramOfInterest, Leads.HighestEducationLevel, Leads.LeadNumber from LeadSources inner join Leads on Leads.LeadSourceNumber=LeadSources.LeadSourceNumber join ClientCustomFieldPrograms on Leads.ClientCustomFieldProgramsNumber=ClientCustomFieldPrograms.ClientCustomFieldProgramsNumber join ClientCustomFields on ClientCustomFieldPrograms.ClientCustomFieldsNumber=ClientCustomFields.ClientCustomFieldsNumber where Leads.EmailAddress in ('beloved1965#charter.net') AND Year (Leads.LeadDate)=2011 and ClientCustomFields.CommonName LIKE '%Ashford%' and Leads.LeadStatus='sent' order by Leads.EmailAddress
The second query
/****** Script for SelectTopNRows command from SSMS ******/
SELECT
CASE
WHEN CustomFieldsXML.value('(/Salutation/node())[1]', 'varchar(max)') = 'Mr.' THEN 'Male'
WHEN CustomFieldsXML.value('(/Salutation/node())[1]', 'varchar(max)') = 'Mrs.' THEN 'Female'
WHEN CustomFieldsXML.value('(/Salutation/node())[1]', 'varchar(max)') = 'Ms.' THEN 'Female'
ELSE 'Unknown' END as Gender, dbo.ClientLeadDistribution.LeadNumber, dbo.ClientLeadDistribution.Postdate, dbo.ClientLeadDistribution.ClientCustomFieldsNumber, dbo.ClientCustomFields.CommonName, dbo.Leads.LeadSourceNumber, dbo.LeadSources.Name, dbo.Leads.ProgramOfInterest, dbo.Leads.EmailAddress from dbo.ClientLeadDistribution join dbo.Leads on dbo.ClientLeadDistribution.LeadNumber = dbo.Leads.LeadNumber join dbo.LeadSources on dbo.Leads.LeadSourceNumber = dbo.LeadSources.LeadSourceNumber join dbo.ClientCustomFields on dbo.ClientLeadDistribution.ClientCustomFieldsNumber = dbo.ClientCustomFields.ClientCustomFieldsNumber where CustomFieldsXML.exist('/Salutation') = 1 and YEAR (postdate) = 2012 and MONTH (postdate)=1 --and dbo.ClientLeadDistribution.ClientCustomFieldsNumber in (1810,1820,1830,2750,2760,2770) order by PostDate, ClientCustomFieldsNumber
The combination is
Select DISTINCT ClientLeadDistribution.ClientCustomFieldsNumber, Leads.EmailAddress,ClientCustomFields.CommonName , LeadSources.Name, CONVERT(VARCHAR(10), leads.LeadStatusDate,101) AS [MM/DD/YYYY],Leads.Age,Leads.State, Leads.ProgramOfInterest, Leads.HighestEducationLevel, Leads.LeadNumber from LeadSources inner join Leads on Leads.LeadSourceNumber=LeadSources.LeadSourceNumber join ClientCustomFieldPrograms on Leads.ClientCustomFieldProgramsNumber=ClientCustomFieldPrograms.ClientCustomFieldProgramsNumber join ClientCustomFields on ClientCustomFieldPrograms.ClientCustomFieldsNumber=ClientCustomFields.ClientCustomFieldsNumber join ClientLeadDistribution on ClientCustomFields.ClientCustomFieldsNumber=ClientLeadDistribution.ClientCustomFieldsNumber where Leads.EmailAddress in ('beloved1965#charter.net') AND Year (Leads.LeadDate)=2011 and ClientCustomFields.CommonName LIKE '%Fortis%' and Leads.LeadStatus='sent' and ClientLeadDistribution.ClientCustomFieldsNumber =(SELECT ClientLeadDistribution.CustomFieldsXML,CASE
WHEN CustomFieldsXML.value('(/Salutation/node())[1]', 'varchar(max)') = 'Mr.' THEN 'Male'
WHEN CustomFieldsXML.value('(/Salutation/node())[1]', 'varchar(max)') = 'Mrs.' THEN 'Female'
WHEN CustomFieldsXML.value('(/Salutation/node())[1]', 'varchar(max)') = 'Ms.' THEN 'Female'
ELSE 'Unknown' END as Gender from dbo.ClientLeadDistribution join dbo.Leads on dbo.ClientLeadDistribution.LeadNumber = dbo.Leads.LeadNumber join dbo.LeadSources on dbo.Leads.LeadSourceNumber = dbo.LeadSources.LeadSourceNumber join dbo.ClientCustomFields on dbo.ClientLeadDistribution.ClientCustomFieldsNumber = dbo.ClientCustomFields.ClientCustomFieldsNumber where CustomFieldsXML.exist('/Salutation') = 1 AND YEAR (postdate) = 2012 and MONTH (postdate)=1) --and dbo.ClientLeadDistribution.ClientCustomFieldsNumber in (1810,1820,1830,2750,2760,2770)--order by ClientCustomFields.CommonName--order by Leads.EmailAddress
And Finally I get this error I tried stuff but nothing seems to work. Any help or suggestions appreciated.
Your subquery is returning 2 fields: "CustomFieldsXML" and "gender".
The error is telling you that you cannot have it return 2 fields. I think you are only after the "gender" so remove the first.

Resources