Making it more dynamic...there might be few thing we can eliminate....rite now its just a working idea
CREATE TABLE dbo.EmpDate_Shift
(
EMPID INT,
[01-Apr-2011] VARCHAR(50),
[02-Apr-2011] VARCHAR(50),
[03-Apr-2011] VARCHAR(50),
[04-Apr-2011] VARCHAR(50),
[05-Apr-2011] VARCHAR(50),
[06-Apr-2011] VARCHAR(50)
)
INSERT INTO EmpDate_Shift
SELECT 1,'Shift1','Shift2','Shift3','Shift4','Shift5','Shift6'
UNION ALL SELECT 2,'Shift1','Shift2','Shift3','Shift4','Shift5','Shift6'
UNION ALL SELECT 3,'Shift1','Shift2','Shift3','Shift4','Shift5','Shift6'
UNION ALL SELECT 4,'Shift1','Shift2','Shift3','Shift4','Shift5','Shift6'
UNION ALL SELECT 5,'Shift1','Shift2','Shift3','Shift4','Shift5','Shift6'
CREATE TABLE dbo.EmpDate
(
EMPID INT,
Dates VARCHAR(50)
)
INSERT INTO EmpDate
SELECT 1, '1-Apr-2011'
UNION ALL SELECT 1, '2-Apr-2011'
UNION ALL SELECT 1, '3-Apr-2011'
UNION ALL SELECT 1, '4-Apr-2011'
UNION ALL SELECT 1, '5-Apr-2011'
UNION ALL SELECT 1, '6-Apr-2011'
UNION ALL SELECT 2, '1-Apr-2011'
UNION ALL SELECT 2, '2-Apr-2011'
UNION ALL SELECT 2, '3-Apr-2011'
UNION ALL SELECT 2, '4-Apr-2011'
UNION ALL SELECT 2, '5-Apr-2011'
UNION ALL SELECT 2, '6-Apr-2011'
UNION ALL SELECT 3, '1-Apr-2011'
UNION ALL SELECT 3, '2-Apr-2011'
UNION ALL SELECT 3, '3-Apr-2011'
UNION ALL SELECT 3, '4-Apr-2011'
UNION ALL SELECT 3, '5-Apr-2011'
UNION ALL SELECT 3, '6-Apr-2011'
UNION ALL SELECT 4, '1-Apr-2011'
UNION ALL SELECT 4, '2-Apr-2011'
UNION ALL SELECT 4, '3-Apr-2011'
UNION ALL SELECT 4, '4-Apr-2011'
UNION ALL SELECT 4, '5-Apr-2011'
UNION ALL SELECT 4, '6-Apr-2011'
UNION ALL SELECT 5, '1-Apr-2011'
UNION ALL SELECT 5, '2-Apr-2011'
UNION ALL SELECT 5, '3-Apr-2011'
UNION ALL SELECT 5, '4-Apr-2011'
UNION ALL SELECT 5, '5-Apr-2011'
UNION ALL SELECT 5, '6-Apr-2011'
SELECT Name As Date INTO EmpDateCol
FROM syscolumns WHERE id IN (SELECT object_id FROM sys.tables WHERE name = 'EmpDate_Shift')
AND ISDate(Name) = 1
CREATE TABLE dbo.EmpDateShift
(
EmpId INT,
Dates VARCHAR(25),
Shift VARCHAR(25)
)
--SELECT * FROM EmpDateCol
--SELECT * FROM EmpDate
--SELECT * FROM EmpDate_Shift
DECLARE @Sql VARCHAR(8000), @Val VARCHAR(50)
SET @Sql = ''
DECLARE cur_Date CURSOR FOR SELECT [Date] FROM EmpDateCol
OPEN cur_Date
FETCH NEXT FROM cur_Date INTO @Val
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @Sql = @Sql + 'SELECT B.EmpID,'''+ @Val + ''',C.[' + @Val + '] FROM EmpDateCol A INNER JOIN Fankarian..EmpDate B ON CONVERT(Date,A.Date) = CONVERT(Date,B.Dates)
INNER JOIN EmpDate_Shift C ON C.Empid = B.EmpID WHERE CONVERT(Date,B.Dates) = CONVERT(Date,''' + @Val + ''') UNION ALL' + CHAR(13)
--INSERT INTO EmpDateShift
--EXEC (@Sql)
FETCH NEXT FROM cur_Date INTO @Val
END
CLOSE cur_Date
DEALLOCATe cur_Date
SET @Sql = LEFT(@Sql,LEN(@Sql)-10)
INSERT INTO EmpDateShift
EXEC (@Sql)
SELECT * FROM EmpDateShift ORDER BY EmpID, Dates
DROP TABLE EmpDateShift
DROP TABLE EmpDate_Shift
DROP TABLE EmpDate
DROP TABLE EmpDateCol