Braking( split ) one row in multiples row - sql

I have a database that works as a logbook for employees on SQL Server 2005. All of the information is filled up at the end of the month in one single table. It has check-in morning, check-out morning, check-in afternoon, check-out afternoon, and comment.
As requested the structure of the table goes as follow:
USE [BitacoraTrabajo]
GO
/****** Objeto: Table [dbo].[B_Bitacora] Fecha de la secuencia de comandos: 07/28/2014 10:25:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[B_Bitacora](
[BBIT_IdBitacora] [int] IDENTITY(1,1) NOT NULL,
[BUSU_IdUsuario] [int] NOT NULL,
[BBIT_Fecha] [datetime] NOT NULL,
[BBIT_01ManEntra] [datetime] NULL,
[BBIT_01ManSale] [datetime] NULL,
[BBIT_01TarEntra] [datetime] NULL,
[BBIT_01TarSale] [datetime] NULL,
[BBIT_01Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_02ManEntra] [datetime] NULL,
[BBIT_02ManSale] [datetime] NULL,
[BBIT_02TarEntra] [datetime] NULL,
[BBIT_02TarSale] [datetime] NULL,
[BBIT_02Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_03ManEntra] [datetime] NULL,
[BBIT_03ManSale] [datetime] NULL,
[BBIT_03TarEntra] [datetime] NULL,
[BBIT_03TarSale] [datetime] NULL,
[BBIT_03Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_04ManEntra] [datetime] NULL,
[BBIT_04ManSale] [datetime] NULL,
[BBIT_04TarEntra] [datetime] NULL,
[BBIT_04TarSale] [datetime] NULL,
[BBIT_04Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_05ManEntra] [datetime] NULL,
[BBIT_05ManSale] [datetime] NULL,
[BBIT_05TarEntra] [datetime] NULL,
[BBIT_05TarSale] [datetime] NULL,
[BBIT_05Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_06ManEntra] [datetime] NULL,
[BBIT_06ManSale] [datetime] NULL,
[BBIT_06TarEntra] [datetime] NULL,
[BBIT_06TarSale] [datetime] NULL,
[BBIT_06Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_07ManEntra] [datetime] NULL,
[BBIT_07ManSale] [datetime] NULL,
[BBIT_07TarEntra] [datetime] NULL,
[BBIT_07TarSale] [datetime] NULL,
[BBIT_07Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_08ManEntra] [datetime] NULL,
[BBIT_08ManSale] [datetime] NULL,
[BBIT_08TarEntra] [datetime] NULL,
[BBIT_08TarSale] [datetime] NULL,
[BBIT_08Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_09ManEntra] [datetime] NULL,
[BBIT_09ManSale] [datetime] NULL,
[BBIT_09TarEntra] [datetime] NULL,
[BBIT_09TarSale] [datetime] NULL,
[BBIT_09Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_10ManEntra] [datetime] NULL,
[BBIT_10ManSale] [datetime] NULL,
[BBIT_10TarEntra] [datetime] NULL,
[BBIT_10TarSale] [datetime] NULL,
[BBIT_10Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_11ManEntra] [datetime] NULL,
[BBIT_11ManSale] [datetime] NULL,
[BBIT_11TarEntra] [datetime] NULL,
[BBIT_11TarSale] [datetime] NULL,
[BBIT_11Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_12ManEntra] [datetime] NULL,
[BBIT_12ManSale] [datetime] NULL,
[BBIT_12TarEntra] [datetime] NULL,
[BBIT_12TarSale] [datetime] NULL,
[BBIT_12Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_13ManEntra] [datetime] NULL,
[BBIT_13ManSale] [datetime] NULL,
[BBIT_13TarEntra] [datetime] NULL,
[BBIT_13TarSale] [datetime] NULL,
[BBIT_13Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_14ManEntra] [datetime] NULL,
[BBIT_14ManSale] [datetime] NULL,
[BBIT_14TarEntra] [datetime] NULL,
[BBIT_14TarSale] [datetime] NULL,
[BBIT_14Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_15ManEntra] [datetime] NULL,
[BBIT_15ManSale] [datetime] NULL,
[BBIT_15TarEntra] [datetime] NULL,
[BBIT_15TarSale] [datetime] NULL,
[BBIT_15Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_16ManEntra] [datetime] NULL,
[BBIT_16ManSale] [datetime] NULL,
[BBIT_16TarEntra] [datetime] NULL,
[BBIT_16TarSale] [datetime] NULL,
[BBIT_16Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_17ManEntra] [datetime] NULL,
[BBIT_17ManSale] [datetime] NULL,
[BBIT_17TarEntra] [datetime] NULL,
[BBIT_17TarSale] [datetime] NULL,
[BBIT_17Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_18ManEntra] [datetime] NULL,
[BBIT_18ManSale] [datetime] NULL,
[BBIT_18TarEntra] [datetime] NULL,
[BBIT_18TarSale] [datetime] NULL,
[BBIT_18Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_19ManEntra] [datetime] NULL,
[BBIT_19ManSale] [datetime] NULL,
[BBIT_19TarEntra] [datetime] NULL,
[BBIT_19TarSale] [datetime] NULL,
[BBIT_19Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_20ManEntra] [datetime] NULL,
[BBIT_20ManSale] [datetime] NULL,
[BBIT_20TarEntra] [datetime] NULL,
[BBIT_20TarSale] [datetime] NULL,
[BBIT_20Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_21ManEntra] [datetime] NULL,
[BBIT_21ManSale] [datetime] NULL,
[BBIT_21TarEntra] [datetime] NULL,
[BBIT_21TarSale] [datetime] NULL,
[BBIT_21Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_22ManEntra] [datetime] NULL,
[BBIT_22ManSale] [datetime] NULL,
[BBIT_22TarEntra] [datetime] NULL,
[BBIT_22TarSale] [datetime] NULL,
[BBIT_22Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_23ManEntra] [datetime] NULL,
[BBIT_23ManSale] [datetime] NULL,
[BBIT_23TarEntra] [datetime] NULL,
[BBIT_23TarSale] [datetime] NULL,
[BBIT_23Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_24ManEntra] [datetime] NULL,
[BBIT_24ManSale] [datetime] NULL,
[BBIT_24TarEntra] [datetime] NULL,
[BBIT_24TarSale] [datetime] NULL,
[BBIT_24Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_25ManEntra] [datetime] NULL,
[BBIT_25ManSale] [datetime] NULL,
[BBIT_25TarEntra] [datetime] NULL,
[BBIT_25TarSale] [datetime] NULL,
[BBIT_25Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_26ManEntra] [datetime] NULL,
[BBIT_26ManSale] [datetime] NULL,
[BBIT_26TarEntra] [datetime] NULL,
[BBIT_26TarSale] [datetime] NULL,
[BBIT_26Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_27ManEntra] [datetime] NULL,
[BBIT_27ManSale] [datetime] NULL,
[BBIT_27TarEntra] [datetime] NULL,
[BBIT_27TarSale] [datetime] NULL,
[BBIT_27Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_28ManEntra] [datetime] NULL,
[BBIT_28ManSale] [datetime] NULL,
[BBIT_28TarEntra] [datetime] NULL,
[BBIT_28TarSale] [datetime] NULL,
[BBIT_28Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_29ManEntra] [datetime] NULL,
[BBIT_29ManSale] [datetime] NULL,
[BBIT_29TarEntra] [datetime] NULL,
[BBIT_29TarSale] [datetime] NULL,
[BBIT_29Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_30ManEntra] [datetime] NULL,
[BBIT_30ManSale] [datetime] NULL,
[BBIT_30TarEntra] [datetime] NULL,
[BBIT_30TarSale] [datetime] NULL,
[BBIT_30Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
[BBIT_31ManEntra] [datetime] NULL,
[BBIT_31ManSale] [datetime] NULL,
[BBIT_31TarEntra] [datetime] NULL,
[BBIT_31TarSale] [datetime] NULL,
[BBIT_31Comentario] [varchar](100) COLLATE Modern_Spanish_CI_AS NULL,
CONSTRAINT [PK_B_Bitacora] PRIMARY KEY CLUSTERED
(
[BBIT_IdBitacora] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[B_Bitacora] WITH CHECK ADD CONSTRAINT [FK_B_Bitacora_B_Usuario] FOREIGN KEY([BUSU_IdUsuario])
REFERENCES [dbo].[B_Usuario] ([BUSU_IdUsuario])
GO
ALTER TABLE [dbo].[B_Bitacora] CHECK CONSTRAINT [FK_B_Bitacora_B_Usuario]
For each day I use a stored procedure to fill it up:
EXEC #return_value = [dbo].[Sp_InsertBitacora]
#BUSU_IdUsuario = 1416127,
#BBIT_Fecha = '2014/22/06 00:00:00.000',
#BBIT_01ManEntra = '2014/01/05 07:50:00.000',
#BBIT_01ManSale = '2014/01/05 14:05:00.000',
#BBIT_01TarEntra = '2014/01/05 15:55:00.000',
#BBIT_01TarSale = '2014/01/05 19:10:00.000',
#BBIT_01Comentario = null,
#BBIT_02ManEntra = '2014/02/05 07:51:00.000',
#BBIT_02ManSale = '2014/02/05 14:04:00.000',
#BBIT_02TarEntra = '2014/02/05 15:50:00.000',
#BBIT_02TarSale = '2014/02/05 19:20:00.000',
#BBIT_02Comentario = null,
#BBIT_03ManEntra = '2014/03/05 07:52:00.000',
#BBIT_03ManSale = '2014/03/05 14:06:00.000',
#BBIT_03TarEntra = '2014/03/05 15:57:00.000',
#BBIT_03TarSale = '2014/03/05 19:11:00.000',
#BBIT_03Comentario = null,
#BBIT_04ManEntra = '2014/04/05 07:53:00.000',
#BBIT_04ManSale = '2014/04/05 14:07:00.000',
#BBIT_04TarEntra = '2014/04/05 15:58:00.000',
#BBIT_04TarSale = '2014/04/05 19:13:00.000',
#BBIT_04Comentario = null,
#BBIT_05ManEntra = '2014/05/05 07:54:00.000',
#BBIT_05ManSale = '2014/05/05 14:00:00.000',
#BBIT_05TarEntra = '2014/05/05 15:59:00.000',
#BBIT_05TarSale = '2014/05/05 19:14:00.000',
#BBIT_05Comentario = null,
#BBIT_06ManEntra = null,
#BBIT_06ManSale = null,
#BBIT_06TarEntra = null,
#BBIT_06TarSale = null,
#BBIT_06Comentario = 'Fin de Semana',
#BBIT_07ManEntra = null,
#BBIT_07ManSale = null,
#BBIT_07TarEntra = null,
#BBIT_07TarSale = null,
#BBIT_07Comentario = 'Fin de Semana',
#BBIT_08ManEntra = '2014/08/05 07:58:00.000',
#BBIT_08ManSale = '2014/08/05 14:02:00.000',
#BBIT_08TarEntra = '2014/08/05 15:58:00.000',
#BBIT_08TarSale = '2014/08/05 19:18:00.000',
#BBIT_08Comentario = null,
#BBIT_09ManEntra = '2014/09/05 07:59:00.000',
#BBIT_09ManSale = '2014/09/05 14:04:00.000',
#BBIT_09TarEntra = '2014/09/05 15:54:00.000',
#BBIT_09TarSale = '2014/09/05 19:19:00.000',
#BBIT_09Comentario = null,
#BBIT_10ManEntra = '2014/10/05 07:40:00.000',
#BBIT_10ManSale = '2014/10/05 14:15:00.000',
#BBIT_10TarEntra = '2014/10/05 15:45:00.000',
#BBIT_10TarSale = '2014/10/05 19:20:00.000',
#BBIT_10Comentario = null,
#BBIT_11ManEntra = '2014/11/05 07:41:00.000',
#BBIT_11ManSale = '2014/11/05 14:11:00.000',
#BBIT_11TarEntra = '2014/11/05 15:46:00.000',
#BBIT_11TarSale = '2014/11/05 19:21:00.000',
#BBIT_11Comentario = null,
#BBIT_12ManEntra = '2014/12/05 07:50:00.000',
#BBIT_12ManSale = '2014/12/05 14:05:00.000',
#BBIT_12TarEntra = '2014/12/05 15:55:00.000',
#BBIT_12TarSale = '2014/12/05 19:10:00.000',
#BBIT_12Comentario = null,
#BBIT_13ManEntra = null,
#BBIT_13ManSale = null,
#BBIT_13TarEntra = null,
#BBIT_13TarSale = null,
#BBIT_13Comentario = 'Fin de Semana',
#BBIT_14ManEntra = null,
#BBIT_14ManSale = null,
#BBIT_14TarEntra = null,
#BBIT_14TarSale = null,
#BBIT_14Comentario = 'Fin de Semana',
#BBIT_15ManEntra = '2014/15/05 07:50:00.000',
#BBIT_15ManSale = '2014/15/05 14:05:00.000',
#BBIT_15TarEntra = '2014/15/05 15:55:00.000',
#BBIT_15TarSale = '2014/15/05 19:10:00.000',
#BBIT_15Comentario = null,
#BBIT_16ManEntra = '2014/16/05 07:50:00.000',
#BBIT_16ManSale = '2014/16/05 14:05:00.000',
#BBIT_16TarEntra = '2014/16/05 15:55:00.000',
#BBIT_16TarSale = '2014/16/05 19:10:00.000',
#BBIT_16Comentario = null,
#BBIT_17ManEntra = '2014/17/05 07:50:00.000',
#BBIT_17ManSale = '2014/17/05 14:05:00.000',
#BBIT_17TarEntra = '2014/17/05 15:55:00.000',
#BBIT_17TarSale = '2014/17/05 19:10:00.000',
#BBIT_17Comentario = null,
#BBIT_18ManEntra = '2014/18/05 07:50:00.000',
#BBIT_18ManSale = '2014/18/05 14:05:00.000',
#BBIT_18TarEntra = '2014/18/05 15:55:00.000',
#BBIT_18TarSale = '2014/18/05 19:10:00.000',
#BBIT_18Comentario = null,
#BBIT_19ManEntra = '2014/19/05 07:50:00.000',
#BBIT_19ManSale = '2014/19/05 14:05:00.000',
#BBIT_19TarEntra = '2014/19/05 15:55:00.000',
#BBIT_19TarSale = '2014/19/05 19:10:00.000',
#BBIT_19Comentario = null,
#BBIT_20ManEntra = null,
#BBIT_20ManSale = null,
#BBIT_20TarEntra = null,
#BBIT_20TarSale = null,
#BBIT_20Comentario = 'Fin de Semana',
#BBIT_21ManEntra = null,
#BBIT_21ManSale = null,
#BBIT_21TarEntra = null,
#BBIT_21TarSale = null,
#BBIT_21Comentario = 'Fin de Semana',
#BBIT_22ManEntra = '2014/22/05 07:50:00.000',
#BBIT_22ManSale = '2014/22/05 14:05:00.000',
#BBIT_22TarEntra = '2014/22/05 15:55:00.000',
#BBIT_22TarSale = '2014/22/05 19:10:00.000',
#BBIT_22Comentario = null,
#BBIT_23ManEntra = '2014/23/05 07:50:00.000',
#BBIT_23ManSale = '2014/23/05 14:05:00.000',
#BBIT_23TarEntra = '2014/23/05 15:55:00.000',
#BBIT_23TarSale = '2014/23/05 19:10:00.000',
#BBIT_23Comentario = null,
#BBIT_24ManEntra = '2014/24/05 07:50:00.000',
#BBIT_24ManSale = '2014/24/05 14:05:00.000',
#BBIT_24TarEntra = '2014/24/05 15:55:00.000',
#BBIT_24TarSale = '2014/24/05 19:10:00.000',
#BBIT_24Comentario = null,
#BBIT_25ManEntra = '2014/25/05 07:50:00.000',
#BBIT_25ManSale = '2014/25/05 14:05:00.000',
#BBIT_25TarEntra = '2014/25/05 15:55:00.000',
#BBIT_25TarSale = '2014/25/05 19:10:00.000',
#BBIT_25Comentario = null,
#BBIT_26ManEntra = '2014/26/05 07:50:00.000',
#BBIT_26ManSale = '2014/26/05 14:05:00.000',
#BBIT_26TarEntra = '2014/26/05 15:55:00.000',
#BBIT_26TarSale = '2014/26/05 19:10:00.000',
#BBIT_26Comentario = null,
#BBIT_27ManEntra = null,
#BBIT_27ManSale = null,
#BBIT_27TarEntra = null,
#BBIT_27TarSale = null,
#BBIT_27Comentario = 'Fin de Semana',
#BBIT_28ManEntra = null,
#BBIT_28ManSale = null,
#BBIT_28TarEntra = null,
#BBIT_28TarSale = null,
#BBIT_28Comentario = 'Fin de Semana',
#BBIT_29ManEntra = '2014/29/05 07:50:00.000',
#BBIT_29ManSale = '2014/29/05 14:05:00.000',
#BBIT_29TarEntra = '2014/29/05 15:55:00.000',
#BBIT_29TarSale = '2014/29/05 19:10:00.000',
#BBIT_29Comentario = null,
#BBIT_30ManEntra = '2014/30/05 07:50:00.000',
#BBIT_30ManSale = '2014/30/05 14:05:00.000',
#BBIT_30TarEntra = '2014/30/05 15:55:00.000',
#BBIT_30TarSale = '2014/30/05 19:10:00.000',
#BBIT_30Comentario = null,
#BBIT_31ManEntra = '2014/31/05 07:50:00.000',
#BBIT_31ManSale = '2014/31/05 14:05:00.000',
#BBIT_31TarEntra = '2014/31/05 15:55:00.000',
#BBIT_31TarSale = '2014/31/05 19:10:00.000',
#BBIT_31Comentario = null
SELECT 'Return Value' = #return_value
GO
The problem is that I need to display this information in a specific format, one row for each day of the month:
Day | CheckinMornig | CheckOutMonrning | CheckInAfternoon | CheckOutAfternoon | Comment
1 | 7:00 pm | 2:00 pm | 4:00 pm | 7:00 pm | none
2 | 7:05 pm | 1:50 pm | 3:55 pm | 7:10 pm | none
3 | null | null | null | null | weekend
4 | null | null | null | null | weekend
...
31 | 7:05 pm | 1:50 pm | 3:55 pm | 7:10 pm | none
I tried to use UNION for each day:
SELECT
LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_01ManEntra, 100), 7)) as CheckInMorning
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_01ManSale, 100), 7)) as CheckOutMorning
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_01TarEntra, 100), 7)) as CheckInAfternoon
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_01TarSale, 100), 7)) as CheckOutAfternoon
,BBIT_01comentario as Comment
FROM [BitacoraTrabajo].[dbo].[B_Bitacora]
where BUSU_IdUsuario = 1416127
union
SELECT
LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_02ManEntra, 100), 7)) as CheckInMorning
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_02ManSale, 100), 7)) as CheckOutMorning
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_02TarEntra, 100), 7)) as CheckInAfternoon
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_02TarSale, 100), 7)) as CheckOutAfternoon
,BBIT_02comentario as Comment
FROM [BitacoraTrabajo].[dbo].[B_Bitacora]
where BUSU_IdUsuario = 1416127
but besides seeming like a very bad idea and a waste of resources, it doesn't work either, because it groups the days that have the same time and the weekends that have nulls.
So, how to get a view or stored procedure with the format that I need?

You could try:
DECLARE #USERID INT = 1416127
DECLARE #FECHA DATETIME = '2014-06-22'
IF OBJECT_ID('dbo.TBL_DESTINATION', 'U') IS NOT NULL DROP TABLE dbo.TBL_DESTINATION
DECLARE TABLE dbo.TBL_DESTINATION (
DAY INT,
CheckInMorning datetime,
CheckOutMorning datetime,
CheckInAfternoon datetime,
CheckOutAfternoon diatomite,
Comentario VARCHAR(250)
)
DECLARE #DAY INT = 1
DECLARE #SQL NVARCHAR(MAX)
WHILE #DAY <= 31
BEGIN
SET #SQL = 'INSERT INTO TBL_DESTINATION SELECT ' + CAST(#DAY as VARCHAR) + ',
LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_' + case when #DAY < 10 then '0' + cast(#DAY as varchar) else cast(#DAY as varchar) end + 'ManEntra, 100), 7)) as CheckInMorning
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_' + case when #DAY < 10 then '0' + cast(#DAY as varchar) else cast(#DAY as varchar) end + 'ManSale, 100), 7)) as CheckOutMorning
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_' + case when #DAY < 10 then '0' + cast(#DAY as varchar) else cast(#DAY as varchar) end + 'TarEntra, 100), 7)) as CheckInAfternoon
,LTRIM(RIGHT(CONVERT(VARCHAR(20), BBIT_' + case when #DAY < 10 then '0' + cast(#DAY as varchar) else cast(#DAY as varchar) end + 'TarSale, 100), 7)) as CheckOutAfternoon
,BBIT_' + case when #DAY < 10 then '0' + cast(#DAY as varchar) else cast(#DAY as varchar) end + 'comentario as Comment
FROM [BitacoraTrabajo].[dbo].[B_Bitacora]
where BUSU_IdUsuario = ' + cast(#USERID as varchar)
' and BBIT_Fecha = ' + cast(#FECHA as varchar)
EXECUTE sp_executesql #SQL
SET #DAY = #DAY + 1
END
SELECT * FROM dbo.TBL_DESTINATION
You will certainly need to define date when the month was closed and the ID of the user who did it. You could create a procedure that would run this code and receive BUSU_IdUsuario and BBIT_Fecha values as parameters. It is up to you if you put this parameters in the SELECT of result of the query or not.

Related

Creating a list of custom Date Ranges for ease of use, in SQL Server

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

SQL Server 2012: Error converting data type nvarchar to float

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.

Remove one table and its alias from the stored procedure

I have a stored procedure in which I don't want to use table which is inward_doc_tracking_trl and its related aliases.
This is the code:
ALTER PROCEDURE [dbo].[GET_INWARD_REMINDER_REPORT]
AS
BEGIN
Select distinct
U.first_name + ' ' + U.last_name UserName,
TH.User_ID, TH.doc_no, TH.U_datetime,
CASE
WHEN TL.U_datetime < DATEADD(d, -5, GETDATE())
THEN M.Reporting_To
ELSE NULL
END Reporting_1 ,
--U.Email AS UserEmail,
--senior.Email AS RA1_Email,
10000 AS UserEmail,
100001 AS RA1_Email,
DATEDIFF(DAY,TH.LastAction_DateTime,GETDATE()) - DATEDIFF(WK,TH.LastAction_DateTime,GETDATE())AS No_Of_Days_Opening
from
inward_doc_tracking_trl TL
inner join
inward_doc_tracking_hdr TH ON TH.mkey = TL.ref_mkey
inner join
user_mst U ON TH.User_Id = U.mkey
inner join
emp_mst M ON M.mkey = U.employee_mkey
outer apply
(select
uss.Email
from
emp_mst MS
inner join
user_mst uss ON uss.employee_mkey = MS.mkey
where
MS.mkey = M.Reporting_To) senior
where
TH.Status_flag NOT IN (5,14)
and TH.To_user IS NOT NULL
END
UPDATE
SCRIPT of the Inward_Doc_Tracking_Hdr table
CREATE TABLE [dbo].[Inward_Doc_Tracking_Hdr](
[Mkey] [numeric](18, 0) NOT NULL,
[FModule_ID] [char](1) NOT NULL,
[Comp_Mkey] [numeric](4, 0) NOT NULL,
[Branch_Mkey] [numeric](4, 0) NOT NULL,
[Tran_Type] [varchar](6) NOT NULL,
[Tran_Code] [numeric](8, 0) NOT NULL,
[Tran_No] [numeric](4, 0) NOT NULL,
[Department_ID] [varchar](4) NOT NULL,
[User_Id] [numeric](10, 0) NULL,
[Doc_Type] [numeric](10, 0) NULL,
[Doc_No] [varchar](30) NULL,
[Doc_Date] [datetime] NOT NULL,
[Dispatch_By] [char](1) NOT NULL,
[Status_Flag] [numeric](8, 0) NOT NULL,
[FA_Year] [smallint] NOT NULL,
[Party_Mkey] [numeric](10, 0) NULL,
[To_Department] [numeric](10, 0) NULL,
[To_User] [numeric](10, 0) NULL,
[Inward_Amt] [numeric](18, 3) NULL,
[Ref_No] [varchar](40) NULL,
[Ref_date] [datetime] NULL,
[U_DateTime] [datetime] NOT NULL,
[LastAction_DateTime] [datetime] NULL,
[Remarks] [varchar](255) NULL,
[Delete_Flag] [char](1) NOT NULL,
[Outward_Type] [char](1) NULL,
[Doc_Department] [numeric](10, 0) NULL,
[Party_Name] [varchar](80) NULL,
[Delivered_By] [varchar](30) NULL,
[Doc_Description] [varchar](50) NULL,
[Last_Department] [numeric](10, 0) NULL,
[Last_User] [numeric](10, 0) NULL,
[Approved_Amount] [float] NULL,
[Chq_No] [varchar](50) NULL,
[Chq_dated] [datetime] NULL,
[Chq_Bank] [varchar](40) NULL,
[Chq_Amount] [float] NULL,
[Vendor_MKey] [int] NULL,
[Vendor_Comp_Mkey] [int] NULL,
[Project_Mkey] [numeric](10, 0) NULL,
[Program_mkey] [numeric](10, 0) NULL,
[Payment_MKey] [int] NULL,
[Due_Date] [datetime] NULL,
[Updated_Remarks] [varchar](500) NULL,
[Updated_Bill_no] [varchar](27) NULL,
[Updated_Bill_Date] [datetime] NULL,
[Updated_Bill_Amt] [float] NULL,
[TotalDeductions] [float] NULL,
[Broker_Mkey] [numeric](10, 0) NULL,
[Customer_Mkey] [numeric](10, 0) NULL,
[Payable_Amt] [float] NULL,
[Balance_Amt] [float] NULL,
[Req_Bill_Flag] [char](1) NULL,
[Po_No] [varchar](50) NULL,
[Receipt_No] [varchar](50) NULL,
[Bill_No] [varchar](50) NULL,
[Org_id] [varchar](10) NULL,
[Site_Id] [varchar](50) NULL,
[Site_Name] [varchar](150) NULL,
[Cumulative_Amt] [numeric](18, 2) NULL,
[Email_Id] [varchar](50) NULL,
[Emp_Id] [varchar](6) NULL,
[Disp_through] [varchar](50) NULL,
[Disp_Through_Name] [varchar](100) NULL,
[Last_To_User] [numeric](10, 0) NULL
) ON [PRIMARY]
removing all reference to inward_doc_tracking_trl, see commented with --##
ALTER PROCEDURE [dbo].[GET_INWARD_REMINDER_REPORT]
AS
BEGIN
Select distinct
U.first_name + ' ' + U.last_name UserName,
TH.User_ID, TH.doc_no, TH.U_datetime,
CASE
--## changed TL.U_datetime to TH.U_datetime
WHEN TH.U_datetime < DATEADD(d, -5, GETDATE())
THEN M.Reporting_To
ELSE NULL
END Reporting_1 ,
--U.Email AS UserEmail,
--senior.Email AS RA1_Email,
10000 AS UserEmail,
100001 AS RA1_Email,
DATEDIFF(DAY,TH.LastAction_DateTime,GETDATE()) - DATEDIFF(WK,TH.LastAction_DateTime,GETDATE())AS No_Of_Days_Opening
--##from
--## inward_doc_tracking_trl TL
--##inner join
--## inward_doc_tracking_hdr TH ON TH.mkey = TL.ref_mkey
from inward_doc_tracking_hdr TH
inner join
user_mst U ON TH.User_Id = U.mkey
inner join
emp_mst M ON M.mkey = U.employee_mkey
outer apply
(select
uss.Email
from
emp_mst MS
inner join
user_mst uss ON uss.employee_mkey = MS.mkey
where
MS.mkey = M.Reporting_To) senior
where
TH.Status_flag NOT IN (5,14)
and TH.To_user IS NOT NULL
END
I think it's enough to remove this code:
inward_doc_tracking_trl TL
inner join
and replace in the case TL with TH
CASE
WHEN TH.U_datetime < DATEADD(d, -5, GETDATE())
THEN M.Reporting_To
ELSE NULL
something like this should be the stored procedure:
ALTER PROCEDURE [dbo].[GET_INWARD_REMINDER_REPORT]
AS
BEGIN
Select distinct
U.first_name + ' ' + U.last_name UserName,
TH.User_ID, TH.doc_no, TH.U_datetime,
CASE
WHEN TH.U_datetime < DATEADD(d, -5, GETDATE())
THEN M.Reporting_To
ELSE NULL
END Reporting_1 ,
--U.Email AS UserEmail,
--senior.Email AS RA1_Email,
10000 AS UserEmail,
100001 AS RA1_Email,
DATEDIFF(DAY,TH.LastAction_DateTime,GETDATE()) - DATEDIFF(WK,TH.LastAction_DateTime,GETDATE())AS No_Of_Days_Opening
from
inward_doc_tracking_hdr TH
inner join
user_mst U ON TH.User_Id = U.mkey
inner join
emp_mst M ON M.mkey = U.employee_mkey
outer apply
(select
uss.Email
from
emp_mst MS
inner join
user_mst uss ON uss.employee_mkey = MS.mkey
where
MS.mkey = M.Reporting_To) senior
where
TH.Status_flag NOT IN (5,14)
and TH.To_user IS NOT NULL
END

SQL Server: set multiple values assigning them default

SET #StartDate = NULL,
#InitialLoopValue=NULL,
#FinalLoopValue = NULL, #RootId = NULL, #MakeId = NULL, #CityId = NULL,
#CountOfCarsUpdated = NULL, #Url = NULL, #MakeName = NULL, #RootName = NULL,
#CityName = NULL, #Content = NULL, #SellInquiryId = NULL, #SellerType = NULL,#imei = NULL;
I have these many variables, and I get this error.
But when I put SET individually for each default assignment its working fine but that's too verbose.
How do I correct this?
You could use SELECT to assign multiple variables at once.
SELECT #StartDate = NULL,
#InitialLoopValue=NULL,
#FinalLoopValue = NULL, #RootId = NULL,
#MakeId = NULL, #CityId = NULL,
#CountOfCarsUpdated = NULL, #Url = NULL,
#MakeName = NULL, #RootName = NULL,
#CityName = NULL, #Content = NULL,
#SellInquiryId = NULL, #SellerType = NULL,#imei = NULL;
Note: Default value for non-assigned variable is NULL so there is no need for = NULL.
DECLARE #v INT;
SELECT #v
-- NULL

Select unique column names from a list of joined tables

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.