Given a date (such as today's date, "October 8th, 2020") and a list of date ranges (Yesterday, Tomorrow, Last Week, Next Week, Last Month, Next Month, etc.), how can we arrive at the necessary date ranges, via SQL.
Yesterday 2020-10-07 00:00:00.000 2020-10-07 23:59:59.000
Tomorrow 2020-10-09 00:00:00.000 2020-10-09 23:59:59.000
Last Week 2020-09-27 00:00:00.000 2020-10-03 23:59:59.000
Next Week 2020-10-11 00:00:00.000 2020-10-17 23:59:59.000
Last Month 2020-09-01 00:00:00.000 2020-09-30 23:59:59.000
Next Month 2020-11-01 00:00:00.000 2020-11-30 23:59:59.000
We have, as a starting point, a Dates table:
CREATE TABLE [dbo].[sysDate](
[DateKey] [int] NOT NULL,
[Date] [datetime] NOT NULL,
[Day] [char](10) NULL,
[DayOfWeek] [smallint] NULL,
[DayOfMonth] [smallint] NULL,
[DayOfYear] [smallint] NULL,
[PreviousDay] [datetime] NULL,
[NextDay] [datetime] NULL,
[WeekOfYear] [smallint] NULL,
[Month] [char](10) NULL,
[MonthOfYear] [smallint] NULL,
[QuarterOfYear] [smallint] NULL,
[Year] [int] NULL,
[FiscalYearString] [varchar](9) NULL,
[FiscalQuarter] [int] NULL,
[FiscalQuarterStartDate] [datetime] NULL,
[FiscalQuarterEndDate] [datetime] NULL,
[FiscalYear] [int] NULL,
[FiscalYearStartDate] [datetime] NULL,
[FiscalYearEndDate] [datetime] NULL
) ON [PRIMARY]
This we created years ago, and populated with data from 1900 to 2030, and it has as an added benefit the identification of Fiscal Periods. Most business use a Fiscal Year that starts April 1, but this isn't always the case.
To address this challenge, we decided that we wanted the flexibility to add new ranges as the need arose, without requiring additional customization of the stored procedures that generated the ranges. We then would need a table to hold the "recipie" for converting a date to its range.
CREATE TABLE [dbo].[CustomDateRanges](
[DateRangeID] [int] IDENTITY(1,1) NOT NULL,
[DateRangeLabel] [varchar](50) NOT NULL,
[DisplayOrder] [int] NULL,
[isPast] [bit] NULL,
[isPresent] [bit] NULL,
[isFuture] [bit] NULL,
[StartDateAdjuster] [varchar](5) NULL,
[StartDayOfWeekAdjuster] [varchar](5) NULL,
[StartDayOfMonthAdjuster] [varchar](5) NULL,
[StartDayOfYearAdjuster] [varchar](5) NULL,
[StartWeekOfYearAdjuster] [varchar](5) NULL,
[StartMonthOfYearAdjuster] [varchar](5) NULL,
[StartQuarterOfYearAdjuster] [varchar](5) NULL,
[StartYearAdjuster] [varchar](5) NULL,
[StartFiscalYearAdjuster] [varchar](5) NULL,
[StartFiscalQuarterAdjuster] [varchar](5) NULL,
[EndDateAdjuster] [varchar](5) NULL,
[EndDayOfWeekAdjuster] [varchar](5) NULL,
[EndDayOfMonthAdjuster] [varchar](5) NULL,
[EndDayOfYearAdjuster] [varchar](5) NULL,
[EndWeekOfYearAdjuster] [varchar](5) NULL,
[EndMonthOfYearAdjuster] [varchar](5) NULL,
[EndQuarterOfYearAdjuster] [varchar](5) NULL,
[EndYearAdjuster] [varchar](5) NULL,
[EndFiscalYearAdjuster] [varchar](5) NULL,
[EndFiscalQuarterAdjuster] [varchar](5) NULL
)
To identify a range, we now declare what manipulations are required to take a given date to the start of its range, and then the same date to the end of its range. NULL columns in the CustomDateRanges table indicate that the field in question does not need any manipulation. Permissible values in the Adjuster columns are:
+<number> -- used to add <number> to the element
-<number> -- used to subtract <number> from the element
<number> -- used to explicitly set the element to <number>
'END' -- used to set the element to its last valid value, but only for "End" adjusters
We added the data to CustomDateRanges
INSERT INTO CustomDateRanges(DateRangeLabel, DisplayOrder, isPast, isPresent, isFuture, StartDateAdjuster, StartDayOfWeekAdjuster, StartDayOfMonthAdjuster, StartDayOfYearAdjuster, StartWeekOfYearAdjuster, StartMonthOfYearAdjuster, StartQuarterOfYearAdjuster, StartYearAdjuster, StartFiscalYearAdjuster, StartFiscalQuarterAdjuster, EndDateAdjuster, EndDayOfWeekAdjuster, EndDayOfMonthAdjuster, EndDayOfYearAdjuster, EndWeekOfYearAdjuster, EndMonthOfYearAdjuster, EndQuarterOfYearAdjuster, EndYearAdjuster, EndFiscalYearAdjuster, EndFiscalQuarterAdjuster)
VALUES
-- DateRangeLabel StartDateAdjuster StartMonthOfYearAdjuster EndDateAdjuster EndMonthOfYearAdjuster
-- | |DisplayOrder| StartDayOfWeekAdjuster | StartQuarterOfYearAdjuster | EndDayOfWeekAdjuster | EndQuarterOfYearAdjuster
-- | | isPast | | StartDayOfMonthAdjuster | StartYearAdjuster | | EndDayOfMonthAdjuster| | EndYearAdjuster
-- | | | isPresent | | StartDayOfYearAdjuster | StartFiscalYearAdjuster | EndDayOfYearAdjuster | | EndFiscalYearAdjuster
-- | | | | isFuture | | | StartWeekOfYearAdjuster | StartFiscalQuarterAdjuster | EndWeekOfYearAdjuster| | EndFiscalQuarterAdjuster
-- | | | | | | | | | | | | | | | | | | | | | | | | |
('Yesterday', NULL, 1, 0, 0, '-1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Today', NULL, 0, 1, 0, '+0', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Tomorrow', NULL, 0, 0, 1, '+1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Last Week', NULL, 1, 0, 0, NULL, '1', NULL, NULL, '-1', NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('This Week', NULL, 0, 1, 0, NULL, '1', NULL, NULL, '+0', NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Next Week', NULL, 0, 0, 1, NULL, '1', NULL, NULL, '+1', NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Last Month', NULL, 1, 0, 0, NULL, NULL, '1', NULL, NULL, '-1', NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('This Month', NULL, 0, 1, 0, NULL, NULL, '1', NULL, NULL, '+0', NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Next Month', NULL, 0, 0, 1, NULL, NULL, '1', NULL, NULL, '+1', NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
,('Last Quarter', NULL, 1, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, '-1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL)
,('This Quarter', NULL, 0, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, '+0', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL)
,('Next Quarter', NULL, 0, 0, 1, NULL, NULL, NULL, NULL, NULL, NULL, '+1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL, NULL)
,('Last Fiscal Quarter', NULL, 1, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '-1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END')
,('This Fiscal Quarter', NULL, 0, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '+0', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END')
,('Next Fiscal Quarter', NULL, 0, 0, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '+1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END')
,('Last Year', NULL, 1, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '-1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL)
,('This Year', NULL, 0, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '+0', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL)
,('Next Year', NULL, 0, 0, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '+1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL, NULL)
,('Last Fiscal Year', NULL, 1, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '-1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL)
,('This Fiscal Year', NULL, 0, 1, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '+0', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL)
,('Next Fiscal Year', NULL, 0, 0, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '+1', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'END', NULL)
Then the code to perform the manipulations. The first step in the code is to strip off the time component (via CAST(CAST(#Date AS Date) AS DateTime), to ensure that lookups against the sysDate table are always accurate, and the last step in the code is to ensure that the StartDate always starts at Midnight, and EndDate always ends at 23:59:59, ensuring complete date ranges.
CREATE PROCEDURE dbo.CalculateCustomDateRange(#Date DateTime, #DateRangeID int, #EndDateIsBeginningOfNextRange bit)
AS
BEGIN
/**************************************************************************************************************************************************
* Copyright: CCD Health Systems
* Written by: Daniel Bragg
* Creation Date: 06-Oct-2020
*
* Updates:
* Date Author Version Purpose
* 2020-Oct-08 Daniel Bragg 5.0.0 Added #EndDateIsBeginningOfNextRange, to permit us to use the output for both
* ([D] >= Start AND [D] <= End) -- #EndDateIsBeginningOfNextRange = 0
* and
* ([D] >= Start AND [D] < End) -- #EndDateIsBeginningOfNextRange = 1
*
*************************************************************************************************************************************************/
SET NOCOUNT ON
DECLARE #StartDate DateTime = CAST(CAST(#Date AS Date) AS DateTime)
DECLARE #EndDate DateTime = #StartDate
-- Values from CustomDateRanges table
DECLARE #DateRangeLabel varchar(50),
#DisplayOrder int,
#isPast bit,
#isPresent bit,
#isFuture bit,
#StartDateAdjuster varchar(5),
#StartDayOfWeekAdjuster varchar(5),
#StartDayOfMonthAdjuster varchar(5),
#StartDayOfYearAdjuster varchar(5),
#StartWeekOfYearAdjuster varchar(5),
#StartMonthOfYearAdjuster varchar(5),
#StartQuarterOfYearAdjuster varchar(5),
#StartYearAdjuster varchar(5),
#StartFiscalYearAdjuster varchar(5),
#StartFiscalQuarterAdjuster varchar(5),
#EndDateAdjuster varchar(5),
#EndDayOfWeekAdjuster varchar(5),
#EndDayOfMonthAdjuster varchar(5),
#EndDayOfYearAdjuster varchar(5),
#EndWeekOfYearAdjuster varchar(5),
#EndMonthOfYearAdjuster varchar(5),
#EndQuarterOfYearAdjuster varchar(5),
#EndYearAdjuster varchar(5),
#EndFiscalYearAdjuster varchar(5),
#EndFiscalQuarterAdjuster varchar(5)
SELECT #DateRangeLabel=DateRangeLabel, #DisplayOrder=DisplayOrder, #isPast=isPast, #isPresent=isPresent, #isFuture=isFuture
, #StartDateAdjuster=StartDateAdjuster, #StartDayOfWeekAdjuster=StartDayOfWeekAdjuster, #StartDayOfMonthAdjuster=StartDayOfMonthAdjuster
, #StartDayOfYearAdjuster=StartDayOfYearAdjuster, #StartWeekOfYearAdjuster=StartWeekOfYearAdjuster, #StartMonthOfYearAdjuster=StartMonthOfYearAdjuster
, #StartQuarterOfYearAdjuster=StartQuarterOfYearAdjuster, #StartYearAdjuster=StartYearAdjuster, #StartFiscalYearAdjuster=StartFiscalYearAdjuster
, #StartFiscalQuarterAdjuster=StartFiscalQuarterAdjuster, #EndDateAdjuster=EndDateAdjuster, #EndDayOfWeekAdjuster=EndDayOfWeekAdjuster
, #EndDayOfMonthAdjuster=EndDayOfMonthAdjuster, #EndDayOfYearAdjuster=EndDayOfYearAdjuster, #EndWeekOfYearAdjuster=EndWeekOfYearAdjuster
, #EndMonthOfYearAdjuster=EndMonthOfYearAdjuster, #EndQuarterOfYearAdjuster=EndQuarterOfYearAdjuster, #EndYearAdjuster=EndYearAdjuster
, #EndFiscalYearAdjuster=EndFiscalYearAdjuster, #EndFiscalQuarterAdjuster=EndFiscalQuarterAdjuster
FROM CustomDateRanges WHERE DateRangeID = #DateRangeID
DECLARE #DayOfWeek smallint,
#DayOfMonth smallint,
#DayOfYear smallint,
#PreviousDay datetime,
#NextDay datetime,
#WeekOfYear smallint,
#MonthOfYear smallint,
#QuarterOfYear smallint,
#Year int,
#FiscalYear int,
#FiscalQuarter int
DECLARE #AdjustFullYears int
DECLARE #AdjustRemainingQuarters int
DECLARE #Value int
--------------------------------
-- Perform Start Calculations --
--------------------------------
-- Set Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
IF (#StartFiscalYearAdjuster IS NOT NULL) AND ISNUMERIC(#StartFiscalYearAdjuster) = 1
BEGIN
SET #Value = CAST(#StartFiscalYearAdjuster AS INT)
IF LEFT(#StartFiscalYearAdjuster,1) = '-' OR LEFT(#StartFiscalYearAdjuster,1) = '+' -- Adjust
SELECT #StartDate=MIN([Date]) FROM sysDate WHERE [FiscalYear]=#FiscalYear+#Value
ELSE
SELECT #StartDate=MIN([Date]) FROM sysDate WHERE [FiscalYear]=#Value
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartFiscalQuarterAdjuster IS NOT NULL) AND ISNUMERIC(#StartFiscalQuarterAdjuster) = 1
BEGIN
SET #Value = CAST(#StartFiscalQuarterAdjuster AS INT)
IF LEFT(#StartFiscalQuarterAdjuster,1) = '-' OR LEFT(#StartFiscalQuarterAdjuster,1) = '+' -- Adjust
BEGIN
-- Simplify
SET #FiscalQuarter=#FiscalQuarter+#Value
WHILE (#FiscalQuarter > 4)
BEGIN
SET #FiscalYear=#FiscalYear+1
SET #FiscalQuarter=#FiscalQuarter-4
END
WHILE (#FiscalQuarter < 1)
BEGIN
SET #FiscalYear=#FiscalYear-1
SET #FiscalQuarter=#FiscalQuarter+4
END
SELECT #StartDate=MIN(FiscalQuarterStartDate) FROM sysDate WHERE [FiscalYear]=#FiscalYear AND [FiscalQuarter]=#FiscalQuarter
END
ELSE
SELECT #StartDate=MIN(FiscalQuarterStartDate) FROM sysDate WHERE [FiscalYear]=#FiscalYear AND [FiscalQuarter]=#Value
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartYearAdjuster IS NOT NULL) AND ISNUMERIC(#StartYearAdjuster) = 1
BEGIN
SET #Value = CAST(#StartYearAdjuster AS INT)
IF LEFT(#StartYearAdjuster,1) = '-' OR LEFT(#StartYearAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEFROMPARTS(#Year+#Value, 1, 1)
ELSE
SET #StartDate = DATEFROMPARTS(#Value, 1, 1)
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartQuarterOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#StartQuarterOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#StartQuarterOfYearAdjuster AS INT)
IF LEFT(#StartQuarterOfYearAdjuster,1) = '-' OR LEFT(#StartQuarterOfYearAdjuster,1) = '+' -- Adjust
BEGIN
SET #StartDate = DATEFROMPARTS(YEAR(#StartDate), 1, 1)
SET #StartDate = DATEADD(quarter, #QuarterOfYear+#Value-1, #StartDate)
END
ELSE
BEGIN
SET #StartDate = DATEFROMPARTS(YEAR(#StartDate), 1, 1)
SET #StartDate = DATEADD(quarter, #Value, #StartDate)
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartMonthOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#StartMonthOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#StartMonthOfYearAdjuster AS INT)
IF LEFT(#StartMonthOfYearAdjuster,1) = '-' OR LEFT(#StartMonthOfYearAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEADD(month, #Value, #StartDate)
ELSE
SET #StartDate = DATEFROMPARTS(YEAR(#StartDate), #Value, DAY(#StartDate))
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartWeekOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#StartWeekOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#StartWeekOfYearAdjuster AS INT)
IF LEFT(#StartWeekOfYearAdjuster,1) = '-' OR LEFT(#StartWeekOfYearAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEADD(week, #Value, #StartDate)
ELSE
SELECT TOP 1 #StartDate=[Date] FROM sysDate WHERE [Year]=#Year AND [WeekOfYear]=#Value ORDER BY [Year],[WeekOfYear],[Date]
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartDayOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#StartDayOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#StartDayOfYearAdjuster AS INT)
IF LEFT(#StartDayOfYearAdjuster,1) = '-' OR LEFT(#StartDayOfYearAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEADD(day, #Value, #StartDate)
ELSE
BEGIN
SET #StartDate = DATEFROMPARTS(YEAR(#StartDate), 1, 1)
SET #StartDate = DATEADD(day, #Value, #StartDate)
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartDayOfMonthAdjuster IS NOT NULL) AND ISNUMERIC(#StartDayOfMonthAdjuster) = 1
BEGIN
SET #Value = CAST(#StartDayOfMonthAdjuster AS INT)
IF LEFT(#StartDayOfMonthAdjuster,1) = '-' OR LEFT(#StartDayOfMonthAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEADD(day, #Value, #StartDate)
ELSE
SET #StartDate = DATEFROMPARTS(YEAR(#StartDate), MONTH(#StartDate), #Value)
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartDayOfWeekAdjuster IS NOT NULL) AND ISNUMERIC(#StartDayOfWeekAdjuster) = 1
BEGIN
SET #Value = CAST(#StartDayOfWeekAdjuster AS INT)
IF LEFT(#StartDayOfWeekAdjuster,1) = '-' OR LEFT(#StartDayOfWeekAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEADD(week, #Value, #StartDate)
ELSE
SELECT #StartDate=[Date] FROM sysDate WHERE [Year]=#Year AND [WeekOfYear]=#WeekOfYear AND [DayOfWeek]=#Value
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
IF (#StartDateAdjuster IS NOT NULL) AND ISNUMERIC(#StartDateAdjuster) = 1
BEGIN
SET #Value = CAST(#StartDateAdjuster AS INT)
IF LEFT(#StartDateAdjuster,1) = '-' OR LEFT(#StartDateAdjuster,1) = '+' -- Adjust
SET #StartDate = DATEADD(day, #Value, #StartDate)
ELSE
SET #StartDate = DATEFROMPARTS(YEAR(#StartDate), MONTH(#StartDate), #Value)
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #StartDate
END
------------------------------
-- Perform End Calculations --
------------------------------
-- NOTE! End Date always starts from the Start Date as its calculation
SET #EndDate=#StartDate
-- Set Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
IF (#EndFiscalYearAdjuster = 'END') OR ((#EndFiscalYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndFiscalYearAdjuster) = 1)
BEGIN
IF (#EndFiscalYearAdjuster = 'END')
SELECT #EndDate=MAX([DATE]) FROM sysDate WHERE [FiscalYear]=#FiscalYear
ELSE IF (#EndFiscalYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndFiscalYearAdjuster) = 1
BEGIN
SET #Value = CAST(#EndFiscalYearAdjuster AS INT)
IF LEFT(#EndFiscalYearAdjuster,1) = '-' OR LEFT(#EndFiscalYearAdjuster,1) = '+' -- Adjust
SELECT #EndDate=[Date] FROM sysDate WHERE [FiscalYear]=#FiscalYear+#Value AND [DayOfYear]=1
ELSE
SELECT #EndDate=[Date] FROM sysDate WHERE [FiscalYear]=#Value AND [DayOfYear]=1
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
IF (#EndFiscalQuarterAdjuster = 'END') OR ((#EndFiscalQuarterAdjuster IS NOT NULL) AND ISNUMERIC(#EndFiscalQuarterAdjuster) = 1)
BEGIN
IF (#EndFiscalQuarterAdjuster = 'END')
SELECT #EndDate=MAX([DATE]) FROM sysDate WHERE [FiscalYear]=#FiscalYear AND [FiscalQuarter]=#FiscalQuarter
ELSE IF (#EndFiscalQuarterAdjuster IS NOT NULL) AND ISNUMERIC(#EndFiscalQuarterAdjuster) = 1
BEGIN
SET #Value = CAST(#EndFiscalQuarterAdjuster AS INT)
IF LEFT(#EndFiscalQuarterAdjuster,1) = '-' OR LEFT(#EndFiscalQuarterAdjuster,1) = '+' -- Adjust
BEGIN
SET #AdjustFullYears = #Value / 4
SET #AdjustRemainingQuarters = #Value % 4
-- Adjust to the beginning of the quarter, to not mess anything up.
SELECT #EndDate=FiscalQuarterEndDate FROM sysDate WHERE [Date]=#EndDate
SET #EndDate=DATEADD(year, #AdjustFullYears, #EndDate)
-- See if we need to adjust the year
IF (#QuarterOfYear + #AdjustRemainingQuarters) > 4
SELECT #EndDate=FiscalQuarterEndDate FROM sysDate WHERE [FiscalYear]=YEAR(#EndDate)+1 AND [FiscalQuarter]=(#FiscalQuarter + #AdjustRemainingQuarters - 4) AND [DayOfMonth]=#DayOfMonth
ELSE IF (#QuarterOfYear + #AdjustRemainingQuarters) < 1
SELECT #EndDate=FiscalQuarterEndDate FROM sysDate WHERE [FiscalYear]=YEAR(#EndDate)-1 AND [FiscalQuarter]=(#FiscalQuarter + #AdjustRemainingQuarters + 4) AND [DayOfMonth]=#DayOfMonth
ELSE
SELECT #EndDate=FiscalQuarterEndDate FROM sysDate WHERE [FiscalYear]=YEAR(#EndDate) AND [FiscalQuarter]=(#FiscalQuarter + #AdjustRemainingQuarters) AND [DayOfMonth]=#DayOfMonth
END
ELSE
SELECT #EndDate=FiscalQuarterEndDate FROM sysDate WHERE [FiscalYear]=YEAR(#EndDate) AND [FiscalQuarter]=#Value AND [DayOfMonth]=#DayOfMonth
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
IF (#EndYearAdjuster = 'END') OR ((#EndYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndYearAdjuster) = 1)
BEGIN
IF (#EndYearAdjuster = 'END')
SELECT #EndDate=MAX([DATE]) FROM sysDate WHERE [Year]=#Year
ELSE IF (#EndYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndYearAdjuster) = 1
BEGIN
SET #Value = CAST(#EndYearAdjuster AS INT)
IF LEFT(#EndYearAdjuster,1) = '-' OR LEFT(#EndYearAdjuster,1) = '+' -- Adjust
SET #EndDate = DATEADD(year, #Value, #EndDate)
ELSE
SET #EndDate = DATEFROMPARTS(#Value, MONTH(#EndDate), DAY(#EndDate))
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
IF (#EndQuarterOfYearAdjuster = 'END') OR ((#EndQuarterOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndQuarterOfYearAdjuster) = 1)
BEGIN
IF (#EndQuarterOfYearAdjuster = 'END')
SELECT #EndDate=MAX([DATE]) FROM sysDate WHERE [Year]=#Year AND [QuarterOfYear]=#QuarterOfYear
ELSE IF (#EndQuarterOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndQuarterOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#EndQuarterOfYearAdjuster AS INT)
IF LEFT(#EndQuarterOfYearAdjuster,1) = '-' OR LEFT(#EndQuarterOfYearAdjuster,1) = '+' -- Adjust
SET #EndDate = DATEADD(quarter, #Value, #EndDate)
ELSE
BEGIN
SET #EndDate = DATEFROMPARTS(YEAR(#EndDate), 1, 1)
SET #EndDate = DATEADD(quarter, #Value, #EndDate)
END
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
IF (#EndMonthOfYearAdjuster = 'END') OR ((#EndMonthOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndMonthOfYearAdjuster) = 1)
BEGIN
IF (#EndMonthOfYearAdjuster = 'END')
SELECT #EndDate=MAX([DATE]) FROM sysDate WHERE [Year]=#Year AND [MonthOfYear]=#MonthOfYear
ELSE IF (#EndMonthOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndMonthOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#EndMonthOfYearAdjuster AS INT)
IF LEFT(#EndMonthOfYearAdjuster,1) = '-' OR LEFT(#EndMonthOfYearAdjuster,1) = '+' -- Adjust
SET #EndDate = DATEADD(month, #Value, #EndDate)
ELSE
SET #EndDate = DATEFROMPARTS(YEAR(#EndDate), #Value, DAY(#EndDate))
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
IF (#EndWeekOfYearAdjuster = 'END') OR ((#EndWeekOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndWeekOfYearAdjuster) = 1)
BEGIN
IF (#EndWeekOfYearAdjuster = 'END')
SELECT #EndDate=MAX([DATE]) FROM sysDate WHERE [Year]=#Year AND [WeekOfYear]=#WeekOfYear
ELSE IF (#EndWeekOfYearAdjuster IS NOT NULL) AND ISNUMERIC(#EndWeekOfYearAdjuster) = 1
BEGIN
SET #Value = CAST(#EndWeekOfYearAdjuster AS INT)
IF LEFT(#EndWeekOfYearAdjuster,1) = '-' OR LEFT(#EndWeekOfYearAdjuster,1) = '+' -- Adjust
SET #EndDate = DATEADD(week, #Value, #EndDate)
ELSE
SELECT TOP 1 #EndDate=[Date] FROM sysDate WHERE [Year]=#Year AND [WeekOfYear]=#Value ORDER BY [Year],[WeekOfYear],[Date]
END
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
-- Removed code for #EndDayOfYearAdjuster, #EndDayOfMonthAdjuster and #EndDayOfWeekAdjuster for brevity, but it's the same as the above code for the matching #Start blocks, but with the extra 'END' processing
IF (#EndDateAdjuster IS NOT NULL) AND ISNUMERIC(#EndDateAdjuster) = 1
BEGIN
-- Nothing is required, the End Date is already the Start Date
-- Update Date Specifics
SELECT #DayOfWeek=[DayOfWeek], #DayOfMonth=[DayOfMonth], #DayOfYear=[DayOfYear], #WeekOfYear=WeekOfYear, #MonthOfYear=[MonthOfYear], #QuarterOfYear=[QuarterOfYear], #Year=[Year], #FiscalYear=[FiscalYear], #FiscalQuarter=[FiscalQuarter] FROM sysDate WHERE [Date] = #EndDate
END
-- Return StartDate as the earliest point on that date
-- and EndDate as the lastest point on that date.
SELECT #Date AS [Date],
#DateRangeID AS [DateRangeID],
#DateRangeLabel AS [DateRangeLabel],
CAST(CAST(#StartDate AS Date) AS DateTime) AS [StartDate],
DATEADD(second, -1, DATEADD(day, 1, CAST(CAST(#EndDate AS Date) AS DateTime))) AS [EndDate]
END
I am using SQL Server 2012. I am running a query that inserts data into a table. I am able to successfully run the query when I comment out the INSERT INTO line, but when I run it with the INSERT INTO code, I get this error:
Msg 8114, Level 16, State 5, Line 27
Error converting data type nvarchar to float.
Code:
DECLARE
#CurrentYear smallint,
#PriorMonth date,
#CurrentMonth date,
#NextMonth date,
#CompanyCode nvarchar(255),
#Delegate varchar(25),
#NAM varchar(2),
#Division varchar(2),
#ReportingPeriod varchar(3)
SELECT
#CurrentYear = DATEPART(YY, GETDATE()),
#PriorMonth = EOMONTH(GETDATE(), -2),
#CurrentMonth = EOMONTH(GETDATE(), -1),
#NextMonth = GETDATE(),
#CompanyCode = 'JDE',
#Delegate = 'Tony Scott',
#NAM = 'US',
#Division = 'MO'
SELECT #ReportingPeriod = dd.FiscalPeriod
FROM dbo.DateDimension dd (NOLOCK)
WHERE dd.LastDayOfMonth = #CurrentMonth
INSERT INTO dbo.GRIR_Main
SELECT
a.CompanyCode,
PriceBlk = '',
QtyBlk = '',
DateBlk = '',
TrPrt = NULL,
POrg = '',
PGr = '',
[Description] = '',
Plant = '',
PlantDescription = '',
PurchReq = '',
RequistionerName = '',
a.GLAcct,
WBSElement = '',
SalesOrder = '',
Network = '',
CostCenter = '',
Reference = '',
a.DocumentNo,
a.ProfitCenter,
a.[Concatenate],
a.Assignment,
a.PurchDoc,
a.VendorType,
Vendor = '',
a.Name1,
Material = '',
ShortText = '',
a.ABSVALAmtinLC,
GRIRUpdated = NULL,
a.AmountinLC,
[Type] = '',
PostingDate = NULL,
a.DaysAged,
a.EYAging,
a.DaysAgedatMonthEnd,
a.EYAgingatMonthEnd,
a.RestatedPriorMonth,
a.EYAgingPriorMonth,
Slippage =
CASE
WHEN a.EYAging = a.EYAgingPriorMonth THEN '0'
ELSE a.EYAging
END,
a.Category1,
a.Analyst,
a.ReportingPeriod,
a.FY,
a.Delegate,
a.NAM,
a.Supplier,
a.Division,
a.Company,
a.CompanyFilter,
a.BU,
a.BusinessUnitDescription,
a.Buyer,
a.OrderNumber,
a.OrderType,
a.Line,
a.ReceiptDate,
a.ReceiptDoc,
a.QuantityReceived,
a.AmountReceived,
a.QuantityVouchered,
a.AmountVouchered,
a.QuantityOpen,
a.AmountOpen,
a.CurCod,
a.BUName,
a.Item,
a.GRIRPeriod,
a.Div
FROM
(SELECT
Delegate = #Delegate,
NAM = #NAM,
Assignment = CAST(j.[Order #] AS VARCHAR) + ' - ' + j.[Order Type] + ' - ' + CAST(j.[Line] AS VARCHAR),
DocumentNo = CAST(j.[Order #] AS VARCHAR),
AmountinLC = j.[Amount Open],
PurchDoc = j.[Order #],
ReportingPeriod = #ReportingPeriod,
FY = #CurrentYear,
Analyst =
CASE
WHEN #CompanyCode IN ('4433', 'PC1') THEN 'Karen Bastek'
WHEN #CompanyCode = '5620' THEN 'Alla O''Hara'
WHEN #CompanyCode = 'JDE' THEN 'Sharon Dooley'
WHEN #CompanyCode IN ('9461', '9462', '9463', '435E', '439Z') THEN 'Irina Shapshevich'
END,
CompanyCode = #CompanyCode,
j.Supplier,
Name1 = j.Name,
VendorType =
CASE
WHEN LEFT(j.Name, 7) = 'Siemens' THEN 'ICC'
ELSE '3rd Party'
END,
Div = j.[DIV #],
j.Company,
CompanyFilter =
CASE
WHEN j.Company IN ('31100','40021') THEN j.Company
ELSE 'All Others'
END,
BU = j.[BU #],
BusinessUnitDescription = j.[Business Unit Description],
j.Buyer,
OrderNumber = j.[Order #],
OrderType = j.[Order Type],
j.Line,
ReceiptDate = CONVERT(varchar(10), j.[Receipt Date], 101),
ReceiptDoc = j.[Receipt Doc],
QuantityReceived = j.[Qty Recvd],
AmountReceived = j.[Amount Rcvd],
QuantityVouchered = j.[Qty Vouchered],
AmountVouchered = j.[Amount Vouchered],
QuantityOpen = j.[Qty Open],
AmountOpen = j.[Amount Open],
CurCod = j.[Curr Code],
ABSVALAmtinLC = ABS(j.[Amount Open]),
Concatenate = CAST(j.Supplier AS VARCHAR) + CAST(j.[Order #] AS VARCHAR) + j.[Order Type] + CAST(CONVERT(varchar(10), j.[Receipt Date], 101) AS VARCHAR) + CAST(j.[Receipt Doc] AS VARCHAR),
DaysAged = DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth),
EYAging =
CASE
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 365 THEN 'h 365 + Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 180 THEN 'g 180 - 365 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 150 THEN 'f 150 - 180 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 120 THEN 'e 120 - 150 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 90 THEN 'd 90 - 120 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 60 THEN 'c 60 - 90 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #CurrentMonth) > 30 THEN 'b 30 - 60 Days'
ELSE 'a Current'
END,
DaysAgedatMonthEnd = DATEDIFF(DAY, j.[Receipt Date], #NextMonth),
EYAgingatMonthEnd =
CASE
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 365 THEN 'h 365 + Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 180 THEN 'g 180 - 365 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 150 THEN 'f 150 - 180 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 120 THEN 'e 120 - 150 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 90 THEN 'd 90 - 120 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 60 THEN 'c 60 - 90 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #NextMonth) > 30 THEN 'b 30 - 60 Days'
ELSE 'a Current'
END,
RestatedPriorMonth = DATEDIFF(DAY, j.[Receipt Date], #PriorMonth),
EYAgingPriorMonth =
CASE
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) < 0 THEN 'False'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 365 THEN 'h 365 + Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 180 THEN 'g 180 - 365 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 150 THEN 'f 150 - 180 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 120 THEN 'e 120 - 150 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 90 THEN 'd 90 - 120 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 60 THEN 'c 60 - 90 Days'
WHEN DATEDIFF(DAY, j.[Receipt Date], #PriorMonth) > 30 THEN 'b 30 - 60 Days'
ELSE 'a Current'
END,
Category1 = j.[Category 1],
GLAcct = CAST(j.[GL Account] AS float),
ProfitCenter = j.[GL Account],
Division = #Division,
BUName = m.[BU Name],
j.Item,
GRIRPeriod = #ReportingPeriod
FROM
dbo.GRIR_JDE j (NOLOCK)
INNER JOIN dbo.MOBusinessSegment m (NOLOCK) ON j.[BU #] = m.PRCTR
) AS a
Here is the table definition that I am trying to insert the data into:
CREATE TABLE [dbo].[GRIR_Main](
[CompanyCode] [varchar](25) NULL,
[PriceBlk] [nvarchar](255) NULL,
[QtyBlk] [nvarchar](255) NULL,
[DateBlk] [nvarchar](255) NULL,
[TrPrt] [float] NULL,
[POrg] [nvarchar](255) NULL,
[PGr] [nvarchar](255) NULL,
[Description] [nvarchar](255) NULL,
[Plant] [nvarchar](255) NULL,
[PlantDescription] [nvarchar](255) NULL,
[PurchReq] [varchar](255) NULL,
[RequistionerName] [nvarchar](255) NULL,
[GLAcct] [float] NULL,
[WBSElement] [nvarchar](255) NULL,
[SalesOrder] [nvarchar](255) NULL,
[Network] [nvarchar](255) NULL,
[CostCenter] [nvarchar](255) NULL,
[Reference] [nvarchar](255) NULL,
[DocumentNo] [nvarchar](255) NULL,
[ProfitCenter] [nvarchar](255) NULL,
[Concatenate] [nvarchar](255) NULL,
[Assignment] [nvarchar](255) NULL,
[PurchDoc] [float] NULL,
[VendorType] [nvarchar](255) NULL,
[Vendor] [nvarchar](255) NULL,
[Name1] [nvarchar](255) NULL,
[Material] [nvarchar](255) NULL,
[ShortText] [nvarchar](255) NULL,
[ABSVALAmtinLC] [float] NULL,
[GRIRUpdated] [float] NULL,
[AmountinLC] [float] NULL,
[Type] [nvarchar](255) NULL,
[PostingDate] [datetime] NULL,
[DaysAged] [float] NULL,
[EYAging] [nvarchar](255) NULL,
[DaysAgedatMonthEnd] [float] NULL,
[EYAgingatMonthEnd] [nvarchar](255) NULL,
[RestatedPriorMonth] [float] NULL,
[EYAgingPriorMonth] [nvarchar](255) NULL,
[Slippage] [nvarchar](255) NULL,
[Category1] [nvarchar](255) NULL,
[Analyst] [nvarchar](255) NULL,
[ReportingPeriod] [nvarchar](255) NULL,
[FY] [float] NULL,
[Delegate] [nvarchar](255) NULL,
[NAM] [nchar](2) NULL,
[Supplier] [nvarchar](255) NULL,
[Division] [nvarchar](255) NULL,
[Company] [nvarchar](255) NULL,
[CompanyFilter] [nvarchar](255) NULL,
[BU] [nvarchar](255) NULL,
[BusinessUnitDescription] [nvarchar](255) NULL,
[Buyer] [nvarchar](255) NULL,
[OrderNumber] [float] NULL,
[OrderType] [nvarchar](255) NULL,
[Line] [float] NULL,
[ReceiptDate] [datetime] NULL,
[ReceiptDoc] [float] NULL,
[QuantityReceived] [float] NULL,
[AmountReceived] [float] NULL,
[QuantityVouchered] [float] NULL,
[AmountVouchered] [float] NULL,
[QuantityOpen] [float] NULL,
[AmountOpen] [float] NULL,
[CurCod] [nvarchar](255) NULL,
[BUName] [nvarchar](255) NULL,
[Item] [nvarchar](255) NULL,
[GRIRPeriod] [nvarchar](255) NULL,
[Div] [nvarchar](255) NULL
) ON [PRIMARY]
I know I have a type mismatch somewhere, but I can't seem to find it. Here is the table definition for the source data.
CREATE TABLE [dbo].[GRIR_JDE](
[Supplier] [float] NULL,
[Name] [nvarchar](255) NULL,
[Order #] [float] NULL,
[Order Type] [nvarchar](255) NULL,
[Category 1] [nvarchar](255) NULL,
[Supplier Type] [nvarchar](255) NULL,
[DIV #] [nvarchar](255) NULL,
[Company] [nvarchar](255) NULL,
[BU #] [nvarchar](255) NULL,
[Business Unit Description] [nvarchar](255) NULL,
[Buyer] [nvarchar](255) NULL,
[Item Branch Buyer] [nvarchar](255) NULL,
[Line] [float] NULL,
[ESN] [nvarchar](255) NULL,
[Item] [nvarchar](255) NULL,
[Receipt Date] [datetime] NULL,
[Qty Recvd] [float] NULL,
[Amount Rcvd] [float] NULL,
[Qty Vouchered] [float] NULL,
[Amount Vouchered] [float] NULL,
[Qty Open] [float] NULL,
[Amount Open] [float] NULL,
[Curr Code] [nvarchar](255) NULL,
[Receipt Doc] [float] NULL,
[GL Account] [nvarchar](255) NULL,
[Time Stamp] [datetime] NULL
) ON [PRIMARY]
If you want to make it run and clean it up later, use one of the try_ functions:
In Sql Server 2012 and up: each of these will return null when the conversion fails instead of an error.
try_convert(datatype,val)
try_cast(val as datatype)
try_parse(val as datatype [using culture])
Check the type of j.[Order #]
you are using it as both a float and nvarchar(255) in:
...
[DocumentNo] [nvarchar](255) NULL,
[PurchDoc] [float] NULL,
...
DocumentNo = j.[Order #],
PurchDoc = j.[Order #],
same problem here:
GLAcct = j.[GL Account],
ProfitCenter = j.[GL Account],
It appears that the CAST of the GL Account field to float failed. I changed the field on the Main table to varchar and it works now.
I have a list of tables that can be joined together by the same PK column. Since this list of tables can vary from project to project, I want to create a query that can be dynamic enough to pull all unique columns from these tables.
For example, I have three tables below:
Table A (PK field, column1, column 2)
Table B (PK field, column3, column 4)
Table C (PK field, column5, column 5)
These three tables are joined on "PK field" column, and I want the query output to be something like:
PK field column1 column2 column3 column4 column5
..data.. ..data.. ..data.. ..data.. ..data.. ..data..
At the end, this query will be part of a SQL function or SP, so the user can define a list of tables, and PK field at the beginning, then executing it shall return my expected output with dataset.
I think about use this query below but the result is not what I like:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ''
Any advice about how I should design this SP or function, will be appreciated.
Thanks in advance.
DDL for two example tables:
CREATE TABLE [dbo].[G_bDEM](
[blaiseKey_code] [nvarchar](255) NULL,
[qSex] [int] NULL,
[qDOB] [datetime] NULL,
[qDOBNR] [int] NULL,
[qAge] [int] NULL,
[qAgeNR] [int] NULL,
[qAgeRange] [int] NULL,
[qAge15OrOver] [int] NULL,
[qNotEligible] [nvarchar](1) NULL,
[qBornInNZ] [int] NULL,
[qCountryOfBirth] [nvarchar](2) NULL,
[qArriveNZYr] [int] NULL,
[qArriveNZYrNR] [int] NULL,
[qArriveNZMth] [int] NULL,
[bDEM_BOP_qHowManyRaised] [int] NULL,
[bDEM_BOP_q1stParentBornNZ] [int] NULL,
[bDEM_BOP_q2ndParentBornNZ] [int] NULL,
[bDEM_BOP_qHowManyParentBornNZ] [int] NULL,
[qMaoriDescent] [int] NULL,
[qSchQual] [int] NULL,
[qSchQualOth] [nvarchar](200) NULL,
[qSchQualOthNR] [int] NULL,
[qSchQualYr] [int] NULL,
[qSchQualYrNR] [int] NULL,
[qPostSchQual] [int] NULL,
[q3MthsStudy] [int] NULL,
[qHighestQual] [int] NULL,
[qHighestQualOth] [nvarchar](200) NULL,
[qHighestQualOthNR] [int] NULL,
[qHighestQualYr] [int] NULL,
[qHighestQualYrNR] [int] NULL,
[qWorkIntro] [nvarchar](1) NULL,
[qDidPaidWork] [int] NULL,
[qAwayFromWork] [int] NULL,
[qFamilyBusWork] [int] NULL,
[bDEM_WOR_qPaidWorkIntro] [nvarchar](1) NULL,
[bDEM_WOR_qJobsNum] [int] NULL,
[bDEM_WOR_qJobsNumNR] [int] NULL,
[bDEM_WOR_tabDEM_T2_fTotMins] [int] NULL,
[bDEM_WOR_q2JobsNoHrsIntro] [nvarchar](1) NULL,
[bDEM_WOR_q2Jobs2HrsIntro] [nvarchar](1) NULL,
[bDEM_WOR_q2Jobs1HrsIntro] [nvarchar](1) NULL,
[bDEM_WOR_qOccupation] [nvarchar](200) NULL,
[bDEM_WOR_qOccupationNR] [int] NULL,
[bDEM_WOR_qMainTasks] [nvarchar](200) NULL,
[bDEM_WOR_qMainTasksNR] [int] NULL,
[bDEM_WOR_qFeelAboutJob] [int] NULL,
[bDEM_WOR_qEmployArrangement] [int] NULL,
[bDEM_WOR_qPermEmployee] [int] NULL,
[qHasJobToStart] [int] NULL,
[qLookedForWork] [int] NULL,
[qJobSearchA] [int] NULL,
[qJobSearchB] [int] NULL,
[qJobSearchC] [int] NULL,
[qJobSearchD] [int] NULL,
[qJobSearchE] [int] NULL,
[qJobSearchF] [int] NULL,
[qJobSearchG] [int] NULL,
[qJobSearchH] [int] NULL,
[qJobSearchI] [int] NULL,
[qJobSearchOth] [nvarchar](200) NULL,
[qJobSearchOthNR] [int] NULL,
[qCouldStartLastWk] [int] NULL,
[qIncTotalAmt] [int] NULL,
[fCountryName] [nvarchar](60) NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[G_bLWW](
[blaiseKey_code] [nvarchar](255) NULL,
[qThingsWorthwhileScale] [int] NULL
) ON [PRIMARY]
This script generate dynamic SQL for any table with similar PK name.
Query:
SET NOCOUNT ON
IF OBJECT_ID (N'dbo.A') IS NOT NULL
DROP TABLE dbo.A
IF OBJECT_ID (N'dbo.B') IS NOT NULL
DROP TABLE dbo.B
IF OBJECT_ID (N'dbo.C') IS NOT NULL
DROP TABLE dbo.C
CREATE TABLE dbo.A (PK_field INT PRIMARY KEY, column1 INT, column2 INT)
CREATE TABLE dbo.B (PK_field INT PRIMARY KEY, column3 INT, column4 INT)
CREATE TABLE dbo.C (PK_field INT PRIMARY KEY, column5 INT, [column 6] INT)
INSERT INTO dbo.A (PK_field, column1, column2)
VALUES (1, 1, 2), (2, 1, 2)
INSERT INTO dbo.B (PK_field, column3, column4)
VALUES (2, 3, 4)
INSERT INTO dbo.C (PK_field, column5, [column 6])
VALUES (1, 5, 6), (3, 5, 6)
DECLARE #SQL NVARCHAR(MAX)
;WITH cte AS
(
SELECT
column_name = '[' + c.name + ']'
, table_name = '[' + s.name + '].[' + o.name + ']'
FROM sys.columns c WITH (NOLOCK)
JOIN sys.objects o WITH (NOLOCK) ON c.[object_id] = o.[object_id]
JOIN sys.schemas s WITH (NOLOCK) ON o.[schema_id] = s.[schema_id]
WHERE o.name IN ('A', 'B', 'C')
AND s.name = 'dbo'
AND o.[type] = 'U'
), unicol AS (
SELECT TOP 1 column_name
FROM cte
GROUP BY cte.column_name
HAVING COUNT(cte.column_name) > 1
), cols AS
(
SELECT DISTINCT column_name
FROM cte
), tbl AS
(
SELECT DISTINCT table_name
FROM cte
), rs AS
(
SELECT
tbl.table_name
, column_name = ISNULL(cte.column_name, cols.column_name + ' = NULL')
FROM cols
CROSS JOIN tbl
LEFT JOIN cte ON cols.column_name = cte.column_name AND cte.table_name = tbl.table_name
), rs2 AS (
SELECT uni = ' UNION ALL' + CHAR(13) + 'SELECT ' + STUFF((
SELECT ', ' + rs.column_name
FROM rs
WHERE tbl.table_name = rs.table_name
GROUP BY rs.column_name
ORDER BY rs.column_name
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') +
' FROM ' + table_name
FROM tbl
)
SELECT #SQL = 'SELECT
' + STUFF((
SELECT CHAR(13) + ', ' + ISNULL(unicol.column_name, cols.column_name + ' = MAX(' + cols.column_name + ')')
FROM cols
LEFT JOIN unicol ON cols.column_name = unicol.column_name
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ' ')
+ '
FROM
(' + STUFF((
SELECT CHAR(10) + uni
FROM rs2
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 11, '') + CHAR(13) +
') t
GROUP BY ' + (SELECT column_name FROM unicol)
PRINT #SQL
EXECUTE sys.sp_executesql #SQL
Output:
SELECT
[column 6] = MAX([column 6])
, [column1] = MAX([column1])
, [column2] = MAX([column2])
, [column3] = MAX([column3])
, [column4] = MAX([column4])
, [column5] = MAX([column5])
, [PK_field]
FROM (
SELECT [column 6] = NULL, [column1], [column2], [column3] = NULL, [column4] = NULL, [column5] = NULL, [PK_field] FROM [dbo].[A]
UNION ALL
SELECT [column 6] = NULL, [column1] = NULL, [column2] = NULL, [column3], [column4], [column5] = NULL, [PK_field] FROM [dbo].[B]
UNION ALL
SELECT [column 6], [column1] = NULL, [column2] = NULL, [column3] = NULL, [column4] = NULL, [column5], [PK_field] FROM [dbo].[C]
) t
GROUP BY [PK_field]
Results:
column 6 column1 column2 column3 column4 column5 PK_field
----------- ----------- ----------- ----------- ----------- ----------- -----------
6 1 2 NULL NULL 5 1
NULL 1 2 3 4 NULL 2
6 NULL NULL NULL NULL 5 3
Update in script:
DECLARE #SQL NVARCHAR(2000) -> NVARCHAR(MAX)
Output for your DDL:
SELECT
[blaiseKey_code]
, [bDEM_BOP_q1stParentBornNZ] = MAX([bDEM_BOP_q1stParentBornNZ])
, [bDEM_BOP_q2ndParentBornNZ] = MAX([bDEM_BOP_q2ndParentBornNZ])
, [bDEM_BOP_qHowManyParentBornNZ] = MAX([bDEM_BOP_qHowManyParentBornNZ])
, [bDEM_BOP_qHowManyRaised] = MAX([bDEM_BOP_qHowManyRaised])
, [bDEM_WOR_q2Jobs1HrsIntro] = MAX([bDEM_WOR_q2Jobs1HrsIntro])
, [bDEM_WOR_q2Jobs2HrsIntro] = MAX([bDEM_WOR_q2Jobs2HrsIntro])
, [bDEM_WOR_q2JobsNoHrsIntro] = MAX([bDEM_WOR_q2JobsNoHrsIntro])
, [bDEM_WOR_qEmployArrangement] = MAX([bDEM_WOR_qEmployArrangement])
, [bDEM_WOR_qFeelAboutJob] = MAX([bDEM_WOR_qFeelAboutJob])
, [bDEM_WOR_qJobsNum] = MAX([bDEM_WOR_qJobsNum])
, [bDEM_WOR_qJobsNumNR] = MAX([bDEM_WOR_qJobsNumNR])
, [bDEM_WOR_qMainTasks] = MAX([bDEM_WOR_qMainTasks])
, [bDEM_WOR_qMainTasksNR] = MAX([bDEM_WOR_qMainTasksNR])
, [bDEM_WOR_qOccupation] = MAX([bDEM_WOR_qOccupation])
, [bDEM_WOR_qOccupationNR] = MAX([bDEM_WOR_qOccupationNR])
, [bDEM_WOR_qPaidWorkIntro] = MAX([bDEM_WOR_qPaidWorkIntro])
, [bDEM_WOR_qPermEmployee] = MAX([bDEM_WOR_qPermEmployee])
, [bDEM_WOR_tabDEM_T2_fTotMins] = MAX([bDEM_WOR_tabDEM_T2_fTotMins])
, [fCountryName] = MAX([fCountryName])
, [q3MthsStudy] = MAX([q3MthsStudy])
, [qAge] = MAX([qAge])
, [qAge15OrOver] = MAX([qAge15OrOver])
, [qAgeNR] = MAX([qAgeNR])
, [qAgeRange] = MAX([qAgeRange])
, [qArriveNZMth] = MAX([qArriveNZMth])
, [qArriveNZYr] = MAX([qArriveNZYr])
, [qArriveNZYrNR] = MAX([qArriveNZYrNR])
, [qAwayFromWork] = MAX([qAwayFromWork])
, [qBornInNZ] = MAX([qBornInNZ])
, [qCouldStartLastWk] = MAX([qCouldStartLastWk])
, [qCountryOfBirth] = MAX([qCountryOfBirth])
, [qDidPaidWork] = MAX([qDidPaidWork])
, [qDOB] = MAX([qDOB])
, [qDOBNR] = MAX([qDOBNR])
, [qFamilyBusWork] = MAX([qFamilyBusWork])
, [qHasJobToStart] = MAX([qHasJobToStart])
, [qHighestQual] = MAX([qHighestQual])
, [qHighestQualOth] = MAX([qHighestQualOth])
, [qHighestQualOthNR] = MAX([qHighestQualOthNR])
, [qHighestQualYr] = MAX([qHighestQualYr])
, [qHighestQualYrNR] = MAX([qHighestQualYrNR])
, [qIncTotalAmt] = MAX([qIncTotalAmt])
, [qJobSearchA] = MAX([qJobSearchA])
, [qJobSearchB] = MAX([qJobSearchB])
, [qJobSearchC] = MAX([qJobSearchC])
, [qJobSearchD] = MAX([qJobSearchD])
, [qJobSearchE] = MAX([qJobSearchE])
, [qJobSearchF] = MAX([qJobSearchF])
, [qJobSearchG] = MAX([qJobSearchG])
, [qJobSearchH] = MAX([qJobSearchH])
, [qJobSearchI] = MAX([qJobSearchI])
, [qJobSearchOth] = MAX([qJobSearchOth])
, [qJobSearchOthNR] = MAX([qJobSearchOthNR])
, [qLookedForWork] = MAX([qLookedForWork])
, [qMaoriDescent] = MAX([qMaoriDescent])
, [qNotEligible] = MAX([qNotEligible])
, [qPostSchQual] = MAX([qPostSchQual])
, [qSchQual] = MAX([qSchQual])
, [qSchQualOth] = MAX([qSchQualOth])
, [qSchQualOthNR] = MAX([qSchQualOthNR])
, [qSchQualYr] = MAX([qSchQualYr])
, [qSchQualYrNR] = MAX([qSchQualYrNR])
, [qSex] = MAX([qSex])
, [qThingsWorthwhileScale] = MAX([qThingsWorthwhileScale])
, [qWorkIntro] = MAX([qWorkIntro])
FROM
(
SELECT [bDEM_BOP_q1stParentBornNZ], [bDEM_BOP_q2ndParentBornNZ], [bDEM_BOP_qHowManyParentBornNZ], [bDEM_BOP_qHowManyRaised], [bDEM_WOR_q2Jobs1HrsIntro], [bDEM_WOR_q2Jobs2HrsIntro], [bDEM_WOR_q2JobsNoHrsIntro], [bDEM_WOR_qEmployArrangement], [bDEM_WOR_qFeelAboutJob], [bDEM_WOR_qJobsNum], [bDEM_WOR_qJobsNumNR], [bDEM_WOR_qMainTasks], [bDEM_WOR_qMainTasksNR], [bDEM_WOR_qOccupation], [bDEM_WOR_qOccupationNR], [bDEM_WOR_qPaidWorkIntro], [bDEM_WOR_qPermEmployee], [bDEM_WOR_tabDEM_T2_fTotMins], [blaiseKey_code], [fCountryName], [q3MthsStudy], [qAge], [qAge15OrOver], [qAgeNR], [qAgeRange], [qArriveNZMth], [qArriveNZYr], [qArriveNZYrNR], [qAwayFromWork], [qBornInNZ], [qCouldStartLastWk], [qCountryOfBirth], [qDidPaidWork], [qDOB], [qDOBNR], [qFamilyBusWork], [qHasJobToStart], [qHighestQual], [qHighestQualOth], [qHighestQualOthNR], [qHighestQualYr], [qHighestQualYrNR], [qIncTotalAmt], [qJobSearchA], [qJobSearchB], [qJobSearchC], [qJobSearchD], [qJobSearchE], [qJobSearchF], [qJobSearchG], [qJobSearchH], [qJobSearchI], [qJobSearchOth], [qJobSearchOthNR], [qLookedForWork], [qMaoriDescent], [qNotEligible], [qPostSchQual], [qSchQual], [qSchQualOth], [qSchQualOthNR], [qSchQualYr], [qSchQualYrNR], [qSex], [qThingsWorthwhileScale] = NULL, [qWorkIntro] FROM [dbo].[G_bDEM]
UNION ALL
SELECT [bDEM_BOP_q1stParentBornNZ] = NULL, [bDEM_BOP_q2ndParentBornNZ] = NULL, [bDEM_BOP_qHowManyParentBornNZ] = NULL, [bDEM_BOP_qHowManyRaised] = NULL, [bDEM_WOR_q2Jobs1HrsIntro] = NULL, [bDEM_WOR_q2Jobs2HrsIntro] = NULL, [bDEM_WOR_q2JobsNoHrsIntro] = NULL, [bDEM_WOR_qEmployArrangement] = NULL, [bDEM_WOR_qFeelAboutJob] = NULL, [bDEM_WOR_qJobsNum] = NULL, [bDEM_WOR_qJobsNumNR] = NULL, [bDEM_WOR_qMainTasks] = NULL, [bDEM_WOR_qMainTasksNR] = NULL, [bDEM_WOR_qOccupation] = NULL, [bDEM_WOR_qOccupationNR] = NULL, [bDEM_WOR_qPaidWorkIntro] = NULL, [bDEM_WOR_qPermEmployee] = NULL, [bDEM_WOR_tabDEM_T2_fTotMins] = NULL, [blaiseKey_code], [fCountryName] = NULL, [q3MthsStudy] = NULL, [qAge] = NULL, [qAge15OrOver] = NULL, [qAgeNR] = NULL, [qAgeRange] = NULL, [qArriveNZMth] = NULL, [qArriveNZYr] = NULL, [qArriveNZYrNR] = NULL, [qAwayFromWork] = NULL, [qBornInNZ] = NULL, [qCouldStartLastWk] = NULL, [qCountryOfBirth] = NULL, [qDidPaidWork] = NULL, [qDOB] = NULL, [qDOBNR] = NULL, [qFamilyBusWork] = NULL, [qHasJobToStart] = NULL, [qHighestQual] = NULL, [qHighestQualOth] = NULL, [qHighestQualOthNR] = NULL, [qHighestQualYr] = NULL, [qHighestQualYrNR] = NULL, [qIncTotalAmt] = NULL, [qJobSearchA] = NULL, [qJobSearchB] = NULL, [qJobSearchC] = NULL, [qJobSearchD] = NULL, [qJobSearchE] = NULL, [qJobSearchF] = NULL, [qJobSearchG] = NULL, [qJobSearchH] = NULL, [qJobSearchI] = NULL, [qJobSearchOth] = NULL, [qJobSearchOthNR] = NULL, [qLookedForWork] = NULL, [qMaoriDescent] = NULL, [qNotEligible] = NULL, [qPostSchQual] = NULL, [qSchQual] = NULL, [qSchQualOth] = NULL, [qSchQualOthNR] = NULL, [qSchQualYr] = NULL, [qSchQualYrNR] = NULL, [qSex] = NULL, [qThingsWorthwhileScale], [qWorkIntro] = NULL FROM [dbo].[G_bLWW]
) t
GROUP BY [blaiseKey_code]
Try this :
DECLARE
#cols VARCHAR(MAX)
, #TableA VARCHAR(10)= 'TableA'
, #TableB VARCHAR(10)= 'TableB'
, #TableC VARCHAR(10)= 'TableC'
, #Pk VARCHAR(20)
SELECT
#cols = STUFF((
SELECT DISTINCT ', [' + c.column_name + ']'
FROM INFORMATION_SCHEMA.Columns c
WHERE c.table_name IN ( #TableA,#TableB,#TableC )
FOR XML PATH('')
), 1, 2, '');
SELECT #Pk = column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = #TableA
DECLARE #query VARCHAR(1000)
SET #query = 'SELECT ' + #cols + ' FROM ' + #TableA + ' JOIN ' + #TableB
+ ' ON ' + #TableA + '.' + #Pk + '=' + #TableB + '.' + #Pk
+ ' JOIN ' + #TableC + ' ON ' + #TableB + '.' + #Pk + '=' + #TableC
+ '.' + #Pk
EXEC (#query)
Do not forget the warning about special html characters in column name given by #Gordon.
You can only do this as a stored procedure. A SQL query returns a specified set of columns, no more, no less. The only way to get a variable number of columns is using dynamic SQL. And, functions don't support dynamic SQL.
You would need to construct a SQL statement, concatenating the column names from INFORMATION_SCHEMA.Columns. Something like this:
declare #cols varchar(max);
select #cols = stuff((select distinct ', ['+c.column_name+']'
from INFORMATION_SCHEMA.Columns c
where c.table_name in (<list of tables here>)
for xml path ('')
), 1, 2, '');
This will not work for column names that have special html characters, such as '<', '>', or '&'.
You can then construct the full query statement and execute it, with exec() or sp_executesql().
An alternative approach would be to create a view that has all the joins and all the columns. Let the SQL optimizer determine the best execution path.