I executed the below query and it executed well :-
SELECT table2id, stuff((select CHAR(13) + table1name from table1 where table1id=table2.table2id FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
from table2 where table2id=117 group by id;
But when I am using count(*) , like in below query :-
SELECT table2id, stuff((select CHAR(13) + count(*) from table1 where table1id=table2.table2id FOR XML PATH (''), TYPE
).value('.', 'varchar(max)')
, 1, 1, '')
from table2 where table2id=117 group by id;
I am getting the below error:
Msg 245, Level 16, State 1, Line 19
Conversion failed when converting the varchar value '
' to data type int.
Now how can I stuff all the columns in table1 ? could anyone help !
I want my result like below:-
table2id | table1name | table1id | table1color
------------------------------------------------------
117 | jon, jack | 117,117 | blue,red
( I am adding my sample data for table1 and table2) :-
table1:
table1id | table1name | table1color | table1city | table1animal |...(I
have 25 columns like this !)
--------------------------------------------------------------
117 | jon | blue | city1 | animal1
117 | jack | red | city2 | animal2
table2:
table2id | table2uniqueid
-------------------------
117 | asbn6383hhh3j3837
118 | kf9s8sujfu6df5d7j
This has nothing to do with stuff.
The reason you get the error is this:
count(*) returns an int. char(13) is a char. Whenever you try to do int + char SQL Server will try to implicitly convert the char to an int. Naturally, char(13) cannot be converted to an int.
What you need to to explicitly convert the count(*) to varchar:
SELECT table2id, stuff(
(
select CHAR(13) + cast(count(*) as varchar(10))
from table1
where table1id=table2.table2id
FOR XML PATH (''), TYPE).value('.', 'varchar(max)'), 1, 1, '')
from table2
where table2id=117
group by id;
Try this code it will helps you by using Dynamic Sql
Firstly i created Two physical Tables with sample data
CREATE TABLE Table1 (table1id INT , table1name Varchar(100) , table1color Varchar(100) , table1city Varchar(100) , table1animal Varchar(100))
INSERT INTO Table1
SELECT 117, 'jon' , 'blue' , 'city1' , 'animal1' UNION ALL
SELECT 117, 'jack', 'red' , 'city2' , 'animal2'
CREATE TABLE Table2( table2id INT, table2uniqueid nvarchar(1000))
INSERT INTO Table2
SELECT 117,'asbn6383hhh3j3837' Union all
SELECT 118,'kf9s8sujfu6df5d7j'
Dynamic Sql code to get the expected result
SET NOCOUNT ON
IF OBJECT_ID('Tempdb..#TEMP') IS NOT NULL
DROP TABLE #TEMP
CREATE TABLE #TEMP(ID INT IDENTITY ,Query nvarchar(max))
IF OBJECT_ID('Tempdb..#TEMP2') IS NOT NULL
DROP TABLE #TEMP2
CREATE TABLE #TEMP2(ID INT IDENTITY ,Query nvarchar(max))
DECLARE #MinID INT,
#MaxID INT,
#Sql nvarchar(max),
#Getcolumn nvarchar(max),
#Sql2 nvarchar(max),
#CteSql nvarchar(max),
#CteSql2 nvarchar(max),
#FullSql nvarchar(max)
DEClare #COlumn Table
(
ID INT IDENTITY,
COlumnname varchar(100)
)
INSERT into #COlumn(COlumnname)
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME='Table1'
SELECT #MinID=MIn(Id),#MaxID=MAX(ID)FRom #COlumn
While (#MinID <=#MaxID)
Begin
SELECT #Getcolumn=COlumnname From #COlumn WHERE ID=#MinID
SET #Sql=N' STUFF((SELECT '', ''+ CAST('+#Getcolumn +' AS VARCHAR(5))
FROM cte AS i
WHERE i.table1id=o.table1id For XML PATH ('''')),1,1,'''') AS '+#Getcolumn
INSERT INTO #TEMP(Query)
SELECT #Sql
SET #MinID=#MinID+1
END
SELECT DISTINCT #Sql2=
STUFF((SELECT ', '+ CAST(Query AS nvarchar(max)) FROM #TEMP i For Xml Path(''), type
).value('.', 'nvarchar(max)')
, 1, 2, '')
FROM #TEMP o
SET #Sql2=#Sql2 +' FRom Cte o'
SET #CteSql= 'SELECT Top 1 '+''' ;With cte
AS
(SELECT T2.table2id,''+ STUFF((SELECT '', ''+''T1.''+COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME=''Table1'' For XML PATH ('''')),1,1,'''') +'' From Table2 T2
LEFT JOIN Table1 T1
On T1.table1id=t2.table2id )''' +'+CHAR(13)+CHAR(10)+'+'''SELECT DISTINCT table2id,''
FROM INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME=''Table1'''
INSERT INTO #TEMP2(Query)
EXECUTE(#CteSql)
SELECT #CteSql2= Query From #TEMP2
SET #FullSql=#CteSql2+#Sql2
PRINT #FullSql
EXEC(#FullSql)
SET NOCOUNT OFF
Result After Running the Query
table2id table1id table1name table1color table1city table1animal
---------------------------------------------------------------------------------------
117 117, 117 jon, jack blue, red city1, city2 anima, anima
118 NULL NULL NULL NULL NULL
Related
I have been able to successfully pivot different field values into separate columns but what I want is to concatenate all of those separate (pivoted) columns into one column. I don't know how many pivoted columns that I end up with at runtime so I can't just use Column1 + Column2 + Column3 etc.
Here is my sql
--Create a table variable to hold my source data
declare #datatable table
(
OrderId int,
ProductId int,
ClientName varchar(50)
)
--insert some data
insert into #datatable values (1, 2, 'Joe Bloggs')
insert into #datatable values (1, 2, 'Frank Bloggs')
--Create a temp table
--that introduces a new field (called Header)
--to give me column names for my pivoted data
IF OBJECT_ID('tempdb..#PivotedClients') IS NOT NULL DROP TABLE #PivotedClients
create table #PivotedClients
(
OrderId int,
ProductId int,
ClientName varchar(50),
Header varchar(100)
)
insert into #PivotedClients
select OrderId,
ProductId,
ClientName,
'Client ' + Cast(Rank() Over (Partition by OrderId
order by ClientName) as varchar(3))
from #datatable
--Create variables to hold my column names
--and my (dynamic) sql
declare #pivotcolumns nvarchar(max),
#colsWithNoNulls nvarchar(max),
#sqlquery nvarchar(max)
set #pivotcolumns = STUFF(
(
select distinct ',' + QUOTENAME(Header)
from #PivotedClients
for XML PATH (''), TYPE
).value('.', 'nvarchar(max)')
,1,1,'')
set #colsWithNoNulls = STUFF(
(
SELECT DISTINCT ',ISNULL(' + QUOTENAME(Header) + ', '''') ' + QUOTENAME(Header)
FROM #PivotedClients
for XML PATH (''), TYPE
).value('.', 'NVARCHAR(max)')
,1,1,''
)
if OBJECT_ID('tempdb..##Clients ') is not null drop TABLE ##Clients
set #sqlquery = 'select distinct OrderId,
ProductID,
' + #colsWithNoNulls + '
into ##Clients
from
(
select OrderId,
ClientName,
ProductID,
Header
from #PivotedClients) x
pivot
(
Max(ClientName)
for Header in (' + #pivotcolumns + ')
) p'
exec sp_executesql #sqlquery
----
select *
from ##Clients
----
The record set that I currently end up with is:
OrderId ProductId Client1 Client 2
1 2 Frank Bloggs Joe Blogs
What I want is:
OrderID ProductId Clients
1 2 Frank Bloggs Joe Bloggs
I don't know how many 'pivoted' columns that I will end up with at runtime so I can't just use Client1 + Client2 etc
Just need to change your #colsWithNoNulls to perform the string concatenation
set #colsWithNoNulls = STUFF(
(
SELECT DISTINCT '+ '' '' + ISNULL(' + QUOTENAME(Header) + ', '''')'
FROM #PivotedClients
for XML PATH (''), TYPE
).value('.', 'NVARCHAR(max)')
, 1, 1, '') + 'AS Clients'
Also you can do a print #sqlquery before sp_executesql. this will helps you debug your dynamic query
Source Table
Col1 |Col2 |Col3 |Col4 | Col5
----------------------------------
hi | this | is | a | test
Destination Table
RowValues|
----------
hi
this
is
a
test
I am using Dynamic SQL.
Any help ?
This is my code , just change table name and the Id in the where clause to what suits you
DECLARE #sql nVARCHAR(max), #TableName nvarchar(100), #where nvarchar(max)
set #TableName = 'stockItems'
set #where= ' where id = 2'
select #sql ='Select '
select #sql = #sql+ + ' '''+ [name] +' = ''+ cast(' + [name] + ' as nvarchar(10)) as '+[name]+', '
from sys.columns where object_name (object_id) = #TableName
set #sql = stuff(#sql, len(#sql), 1, '') + ' From '+#TableName+ #where
print #sql
set #sql = REPLACE(#sql,', From',' From')
set #sql = #sql + ' '
print #sql
exec(#sql)
Now I need to create a new table that has one column that hold holds each value as a row
Thanks to #Mahmoud-Gamal
The solution should be something like below
declare #cols nvarchar(max)
select #cols = STUFF((SELECT distinct ',' +
QUOTENAME(column_name)
FROM information_schema.columns
WHERE table_name = 'vehicles'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
declare #statement nvarchar(max)
set #statement ='
SELECT
ColumnName, Value
FROM
Vehicles
UNPIVOT
(
Value
FOR ColumnName
IN
(
'+#cols+'
)
)
AS A'
execute(#statement)
Please change the "vehicle" table name to any table on your database that has columns from different types (datetime, int and nvarchar) and the below error is shown
Any help ?
The type of column "Description" conflicts with the type of other columns specified in the UNPIVOT list.
Use the UNPIVOT table operator:
SELECT col AS RowValues
FROM table1 AS t
UNPIVOT
(
col
FOR value IN([col1],
[col2],
[col3],
[col4],
[col5])
) AS u;
SQL Fiddle Demo
This will give you:
| ROWVALUES |
|-----------|
| hi |
| this |
| is |
| a |
| test |
Update:
In case you don't know the names of the columns, and you want to do this dynamically, you have to do this using dynamic SQL.
But the problem is how to get the columns names?
You can get the columns names from the information_schema.columns, then concatenate them in one sql, then replace the columns' names in the UNPIVOT with this string, and execute that statement dynamically like this:
DECLARE #cols AS NVARCHAR(MAX);
DECLARE #query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' +
QUOTENAME(column_name)
FROM information_schema.columns
WHERE table_name = 'Table1'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT #query = ' SELECT col AS RowValues
FROM table1 AS t
UNPIVOT
(
val
FOR col IN ( ' + #cols + ' )
) AS u;';
EXECUTE(#query);
Updated SQL Fiddle Demo
I believe you want this
Select Col1 + Col2 + Col3 + Col4 + Col5 From Table
Or may be following
Select Col1 From Table1
union Select Col2 From Table1
union Select Col3 From Table1
union Select Col4 From Table1
union Select Col5 From Table1 ;
Im using MS SQL Server 2008
Table name is tblDateTimeLog:
ID INT(AI)
RecordID INT
DateLog DATE
TimeLog TIME
DetachmentCode INT
EntryDate DATETIME
IsDeleted BIT
UserID VARCHAR(50)
I have a table containing this:
RecordID | DateLog | TimeLog
11 | 2013-06-01 | 07:59:00
11 | 2013-06-01 | 19:01:00
11 | 2013-06-02 | 07:57:00
11 | 2013-06-02 | 19:03:00
11 | 2013-06-03 | 07:49:00
11 | 2013-06-03 | 19:11:00
14 | 2013-06-04 | 08:01:00
14 | 2013-06-04 | 19:03:00
14 | 2013-06-05 | 07:52:00
14 | 2013-06-05 | 19:02:00
One Record ID can have multiple TimeLog on the same DateLog
Now I want it to show like this:
The Dates as columns and the Total No. of Hours between MIN(TimeLog) and MAX(TimeLog)
RecordID | 2013-06-01 | 2013-06-02 | 2013-06-03 | 2013-06-04 | 2013-06-05
11 | 11:02:00 | 11:06:00 | 11:22:00 | NULL | NULL
14 | NULL | NULL | NULL | 11:02:00 | 11:10:00
As per Mikael's Answer, this works but as I understand his query, this returns MIN(TimeLog):
DECLARE #SQL NVARCHAR(MAX)
DECLARE #ColumnList NVARCHAR(MAX)
SELECT #ColumnList =
STUFF
(
(
SELECT DISTINCT ','+QUOTENAME(DateLog)
FROM TESTPIS.dbo.tblDateTimeLog
WHERE IsDeleted=0 AND DateLog >= '2013-06-15' AND DateLog <= '2013-06-30'
ORDER BY 1
FOR XML PATH('')
), 1, 1, ''
)
SET #SQL = 'SELECT P.RecordID, '+#ColumnList+'
FROM
(
SELECT RecordID, TimeLog, DateLog FROM TESTPIS.dbo.tblDateTimeLog WHERE isDeleted=0
) AS T
PIVOT
(
MIN(TimeLog) FOR DateLog IN ('+#ColumnList+')
) as P'
EXEC (#SQL)
What I want to return is like DATEDIFF(MINUTES,MIN(TimeLog),MAX(TimeLog)
I tried replacing the MIN(TimeLog) in the query with this
SUM(DATEDIFF(MINUTES,MIN(TimeLog),MAX(TimeLog))
However, I got this error
Incorrect syntax near '('.
select P.RecordID,
P.[2013-06-01],
P.[2013-06-02],
P.[2013-06-03],
P.[2013-06-04],
P.[2013-06-05]
from (
select RecordID,
TimeLog,
DateLog
from YourTable
) as T
pivot(min(TimeLog) for DateLog in ([2013-06-01],
[2013-06-02],
[2013-06-03],
[2013-06-04],
[2013-06-05])) as P
To build the query dynamically you have to first figure out what the column list should contain.
select distinct DateLog
from YourTable
order by 1
The result from that query has to be turned into a comma separated list and since numbers like that is invalid column names you can use quotename() to enclose the value in [].
To build the comma separated list of column you can use for xml path('').
select stuff((select distinct ','+quotename(DateLog)
from YourTable
order by 1
for xml path('')), 1, 1, '')
stuff() is there to remove the first comma.
Then you just need to put it all together and execute the query you have built.
declare #SQL nvarchar(max)
declare #ColumnList nvarchar(max)
select #ColumnList = stuff((select distinct ','+quotename(DateLog)
from YourTable
order by 1
for xml path('')), 1, 1, '')
set #SQL = '
select P.RecordID, '+#ColumnList+'
from (
select RecordID,
TimeLog,
DateLog
from YourTable
) as T
pivot(min(TimeLog) for DateLog in ('+#ColumnList+')) as P'
exec (#SQL)
SQL Fiddle
Update
To get the diff between max and min timelog value for each day you can do a group by on RecordID and DateLog in the derived table and calculate the diff in seconds between min and max and use that value to calculate a new time value using dateadd.
select P.RecordID,
P.[2013-06-01],
P.[2013-06-02],
P.[2013-06-03],
P.[2013-06-04],
P.[2013-06-05]
from (
select RecordID,
dateadd(second, datediff(second, min(TimeLog), max(TimeLog)), convert(time(0), '00:00')) as TimeDiff,
DateLog
from YourTable
group by RecordID,
DateLog
) as T
pivot(min(TimeDiff) for DateLog in ([2013-06-01],
[2013-06-02],
[2013-06-03],
[2013-06-04],
[2013-06-05])) as P
Dynamic version:
declare #SQL nvarchar(max)
declare #ColumnList nvarchar(max)
select #ColumnList = stuff((select distinct ','+quotename(DateLog)
from YourTable
order by 1
for xml path('')), 1, 1, '')
set #SQL = '
select P.RecordID, '+#ColumnList+'
from (
select RecordID,
dateadd(second, datediff(second, min(TimeLog), max(TimeLog)), convert(time(0), ''00:00'')) as TimeDiff,
DateLog
from YourTable
group by RecordID,
DateLog
) as T
pivot(min(TimeDiff) for DateLog in ('+#ColumnList+')) as P'
exec (#SQL)
SQL Fiddle
Try this one -
Query:
IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
RecordID INT
, DateLog DATETIME
, TimeLog TIME
)
INSERT INTO #temp (RecordID, DateLog, TimeLog)
VALUES
(11, '2013-06-01', '08:00:00'), (11, '2013-06-02', '09:00:00'),
(11, '2013-06-03', '10:00:00'), (11, '2013-06-04', '11:00:00'),
(11, '2013-06-05', '12:00:00'), (14, '2013-06-01', '13:00:00'),
(14, '2013-06-02', '14:00:00'), (14, '2013-06-03', '15:00:00'),
(14, '2013-06-04', '16:00:00')
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'SELECT *
FROM (
SELECT DateLog, RecordID, tt = CAST(TimeLog AS VARCHAR(8))
FROM #temp
) src
PIVOT (
MAX(tt)
FOR DateLog IN (' + STUFF((
SELECT ', [' + CONVERT(VARCHAR(10), DateLog, 120) + ']'
FROM #temp
GROUP BY DateLog
ORDER BY DateLog
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')
) p'
PRINT #SQL
EXEC sys.sp_executesql #SQL
Output:
SELECT *
FROM (
SELECT DateLog, RecordID, tt = CAST(TimeLog AS VARCHAR(8))
FROM #temp
) src
PIVOT (
MAX(tt)
FOR DateLog IN ([2013-06-01], [2013-06-02], [2013-06-03], [2013-06-04], [2013-06-05])
) p
Results:
RecordID 2013-06-01 2013-06-02 2013-06-03 2013-06-04 2013-06-05
----------- ---------- ---------- ---------- ---------- ----------
11 08:00:00 09:00:00 10:00:00 11:00:00 12:00:00
14 13:00:00 14:00:00 15:00:00 16:00:00 NULL
Update with results:
I am writing a trigger and I am using inserted
Inserted is a single row
like
ColumnX |ColumnY|ColumnZ|
=========================
A | B |C |
I want to insert results to another table like this
ColumnName |Value|
==================
ColumnX | A |
ColumnY | B |
ColumnZ | C |
I have a lot of tables how can I make this?
UNPIVOT the result set, then insert them:
INSERT INTO Anothertable(Columnname, value)
SELECT Columnname, value
FROM tablename t
UNPIVOT
(
value
FOR ColumnName IN(ColumnX, ColumnY, ColumnZ)
) AS u;
SQL Fiddle Demo
To do this dymaincally:
DECLARE #cols AS NVARCHAR(MAX);
DECLARE #query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' +
QUOTENAME(Columnname)
FROM table1 t
UNPIVOT
(
value
FOR ColumnName IN(ColumnX, ColumnY, ColumnZ)
) AS u
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SET #query = 'SELECT Columnname, value
FROM table1 t
UNPIVOT
(
value
FOR ColumnName IN( ' + #cols + ' )
) AS u;'
execute(#query);
Updated SQL Fiddle Demo
CREATE TRIGGER TriggerName
ON YourDatabase.TableName
AFTER INSERT
AS
BEGIN
INSERT INTO OtherTable (ColumnX, ColumnY, ColumnZ)
SELECT ColumnX, ColumnY, ColumnZ
FROM inserted
END
GO
I am having one query which returns me following output.
(No of results not same all time, means sometimes it gives 3 category,sometimes 8 category etc..)
CategoryName
Test1
Test2
Test3
Now i want that store procedure should return me these date in comma separated format.
e.g. output string should be like: Test1,Test2,Test3
Can you please tell me how can i achieve this?
this will work for all characters in your data:
set nocount on;
declare #YourTable table (BirthDay datetime, PersonName varchar(20))
insert into #YourTable VALUES ('1-10-2010', 'Joe' )
insert into #YourTable VALUES ('2-10-2010', 'Bob <&>' )
insert into #YourTable VALUES ('2-10-2010', 'Alice')
set nocount off
--Concatenation with FOR XML and eleminating control/encoded character expansion "& < >"
SELECT
p1.BirthDay
,STUFF(
(SELECT
', ' + p2.PersonName
FROM #YourTable p2
WHERE p2.BirthDay=p1.BirthDay
ORDER BY p2.PersonName
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS PersonNames
FROM #YourTable p1
GROUP BY p1.BirthDay
OUTPUT:
BirthDay PersonNames
----------------------- ------------------------
2010-01-10 00:00:00.000 Joe
2010-02-10 00:00:00.000 Alice, Bob <&>
(2 row(s) affected)
Try COALESCE or ISNULL:
DECLARE #returnValue varchar(MAX)
SELECT
#returnValue = COALESCE(#returnValue + ', ', '') + CategoryName
FROM
TableName
Have a look at something like (Full working example)
DECLARE #Table TABLE(
ID INT,
Val VARCHAR(50)
)
INSERT INTO #Table (ID,Val) SELECT 1, 'A'
INSERT INTO #Table (ID,Val) SELECT 1, 'B'
INSERT INTO #Table (ID,Val) SELECT 1, 'C'
INSERT INTO #Table (ID,Val) SELECT 2, 'B'
INSERT INTO #Table (ID,Val) SELECT 2, 'C'
--Concat
SELECT t.ID,
STUFF((
SELECT ',' + t1.Val
FROM #Table AS t1
WHERE t1.ID = t.ID
FOR XML PATH('')
), 1, 1, '')
FROM #Table t
GROUP BY t.ID
Also, you might find that Googling will provide a lot of answers.
One means:
SELECT STUFF((
SELECT ',' + CategoryName AS [text()]
FROM YourTable
FOR XML PATH('')
), 1, 1, '')
...but watch out for XML entities that will be escaped up - e.g. & => &
Just modify the KM answer in a store procedure
ALTER Procedure [dbo].[Payroll_rptAbsentReport]
#FromDate DateTime,
#ToDate DateTime,
#GFacatoryID UniqueIdentifier
As
Begin
-- Temporary table for Row data seperation
CREATE TABLE TestTable(GEmployeeGenInfoID uniqueidentifier, dtAttendDateTime varchar(max))
INSERT INTO
TestTable(GEmployeeGenInfoID, dtAttendDateTime)
SELECT
Payroll_tblAttendance.GEmployeeGenInfoID
,CONVERT(VARCHAR(max), dtAttendDateTime, 105)dtAttendDateTime
FROM Payroll_tblAttendance
INNER JOIN PIS.dbo.PIS_tblEmployeeGenInfo as EmployeeGenInfo ON Payroll_tblAttendance.GEmployeeGenInfoID= EmployeeGenInfo.GEmployeeGenInfoID
WHERE Payroll_tblAttendance.DayStatusID = 0 AND EmployeeGenInfo.GFactoryID=#GFacatoryID AND Payroll_tblAttendance.dtAttendDateTime Between #FromDate and #ToDate ORDER BY dtAttendDateTime
-- Final expected output
SELECT DISTINCT
EmployeeGenInfo.StrEmpName
,EmployeeGenInfo.StrEmpID
,Attendence.CardNo
,EmployeeDesignation.StrDesignationName
,EmployeeDept.StrDepartmentName
-- Count data will be in one column
,(Select COUNT(*) From TestTable Where GEmployeeGenInfoID=Attendence.GEmployeeGenInfoID) TotalAbsent
-- Row data set into one column seperate by coma
,substring( ( SELECT ', ' + dtAttendDateTime as [text()]
FROM TestTable
WHERE GEmployeeGenInfoID = Attendence.GEmployeeGenInfoID
FOR XML path(''), elements
), 3, 1000
) List
FROM
Payroll_tblAttendance as Attendence
INNER JOIN TestTable on TestTable.GEmployeeGenInfoID=Attendence.GEmployeeGenInfoID
INNER JOIN PIS.dbo.PIS_tblEmployeeGenInfo as EmployeeGenInfo ON Attendence.GEmployeeGenInfoID= EmployeeGenInfo.GEmployeeGenInfoID
INNER JOIN PIS.dbo.PIS_tblDesignationInfo as EmployeeDesignation ON EmployeeGenInfo.GDesignationInfoID= EmployeeDesignation.GDesignationInfoID
INNER JOIN PIS.dbo.PIS_tblDepartment as EmployeeDept ON EmployeeGenInfo.GDepartmentID= EmployeeDept.GDepartmentID
WHERE EmployeeGenInfo.GFactoryID=#GFacatoryID AND Attendence.DayStatusID = 0 AND Attendence.dtAttendDateTime Between #FromDate and #ToDate
DROP TABLE TestTable
END