Dynamic SQL- Passing a table name as parameter
Database
1
Posts
1
Posters
0
Views
1
Watching
-
I want to pass a table name as input parameter for the below query. Thank you in Advance
Declare @TableName VARCHAR(255)='MyDepartment'
Select TableName, ExceptionName, count = count(*)
From (
Select DepartmentID, TableName
, ExceptionName = LTRIM(RTRIM(x.d.value('.[1]','varchar(100)')))
From (
Select DepartmentID, TableName = 'MyDepartment'
, xml = CAST('' + REPLACE(Name,';','') + '' AS XML)
From MyDepartment --I want to use @TableName here
)AS TableName
Cross Apply XML.nodes('/Root/Data')x(d)
) AS LIST
Where ExceptionName <> ''
Group By TableName, ExceptionName
Order By TableName, ExceptionName