Count rows in all tables, that meets conditions - sql

I have database with 7,000 tables, most of these have a column DataAreaId, but not all tables, since some are global.
I would like to list all tables that have the column DataAreaId and their row count where the column DataAreaId contains "FR".
So for one table it would be:
SELECT COUNT(*)
FROM Table
WHERE DataAreaId = 'FR'
Any suggestions?

You can use the following
CREATE TABLE T1(
Dataareaid VARCHAR(45)
);
CREATE TABLE T2(
Dataareaid VARCHAR(45)
);
INSERT INTO T1 VALUES
('FR'),
('ALG'),
('FR');
DECLARE #SQL NVARCHAR(max) = N'';
SELECT #SQL = (
SELECT CONCAT(
N'UNION ALL ',
N'SELECT ''',
t.name,
N''' AS TableName, ',
N'Cnt = (SELECT COUNT(1)',
' FROM ',
QUOTENAME(t.name),
N' WHERE [Dataareaid] = ''FR'')'
)
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name = 'Dataareaid'
FOR XML PATH('')
)
SET #SQL = STUFF(#SQL, 1, 10, N'');
EXEC sp_executesql #SQL;
Returns:
+-----------+-----+
| TableName | Cnt |
+-----------+-----+
| T1 | 2 |
| T2 | 0 |
+-----------+-----+
Live Demo

One way to do this is to query all tables containing that column, and build a query statement for each
select 'union all select ' + QUOTENAME(t.name,N'''') + ', count(1) from ' + t.name + ' where Dataareaid = ''FR'''
from sys.columns c
join sys.tables t ON c.object_id = t.object_id
where c.name = 'Dataareaid'
each row would look like this
union all select 'SomeTable', count(1) from SomeTable where Dataareaid = 'FR'
Now just put all statements together and remove the first union all

My answer gets the column metadata, executes the statement in a loop and publishes the results to a table variable:
if object_id('tempdb..#LoopList') is not null
drop table #LoopList
select
s.[name] as SchemaName
,t.[name] as TableName
,row_number() over (order by t.[object_id] asc) as RowNumber
into #LoopList
from sys.columns as c
inner join sys.tables as t
on c.[object_id] = t.[object_id]
inner join sys.schemas as s
on t.[schema_id] = s.[schema_id]
where c.[name] = 'Dataareaid'
declare
#a int = 1
,#b int = (select max(RowNumber) from #LoopList)
,#c nvarchar(max)
,#d nvarchar(max)
,#e int
declare #count table (RowCounter int)
declare #resultsTable table (TableName nvarchar(500), RowCounter int)
while #a <= #b
begin
delete from #count
set #c = concat ((select quotename(SchemaName) from #LoopList where RowNumber = #a)
,'.'
,(select quotename(TableName) from #LoopList where RowNumber = #a)
)
set #d = concat(N'select count(*) from '
,#c
,N' where Dataareaid = ''FR'''
)
insert into #count (
RowCounter
)
exec sp_executesql #d
set #e = (select top 1 RowCounter from #count)
insert into #resultsTable (
TableName
,RowCounter
)
values (#c,#e)
set #a += 1;
end
select * from #resultsTable

Related

Dynamic SQL stored procedure not populating temporary table

I am using a stored procedure with one parameter (#tablename) to generate a table of attributes about the table named via the parameter.
I call the stored procedure as follows
EXEC sp_Schema_Presentation #tablename = 'UserID'
And run the stored procedure (at the bottom of this post).
I have created a #DynamicSQL string in order to use my #tablename parameter. However, the SELECT statement, in which it's used, also creates the #TEMP table.
The rest of the query uses this #TEMP table so I DECLARE its structure at the top.
However, when I run the stored procedure, the #TEMP table is empty
If I hard code the #tablename, the query will work. Any ideas how I can fix this?
Thanks
CREATE TABLE #TEMP
(
SampleKey nvarchar(MAX),
SampleData nvarchar(MAX)
)
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL = N'SELECT B.*
INTO dbo.#TEMP
FROM (
SELECT * FROM ' + #Tablename + N' ORDER BY 1 DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY
) A
CROSS APPLY (
SELECT [Key] AS SampleKey
,Value AS SampleData
FROM OpenJson( (SELECT A.* FOR JSON Path, Without_Array_Wrapper,INCLUDE_NULL_VALUES ) )
) B'
Full stored procedure in SQL Server 2016:
ALTER PROCEDURE [dbo].[sp_Schema_Presentation]
#TableName nvarchar(MAX)
AS
BEGIN
CREATE TABLE #TEMP
(
SampleKey nvarchar(MAX),
SampleData nvarchar(MAX)
)
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL = N'SELECT B.*
INTO dbo.#TEMP
FROM (
SELECT * FROM ' + #Tablename + N' ORDER BY 1 DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY
) A
CROSS APPLY (
SELECT [Key] AS SampleKey
,Value AS SampleData
FROM OpenJson( (SELECT A.* FOR JSON Path, Without_Array_Wrapper,INCLUDE_NULL_VALUES ) )
) B'
DECLARE #Columns as NVARCHAR(MAX)
SELECT #Columns = COALESCE(#Columns + ', ','') + QUOTENAME(COLUMN_NAME)
FROM
(
SELECT COLUMN_NAME FROM PRESENTATION_PP.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N''' + #TableName + '''
) AS B
EXECUTE sp_executesql #DynamicSQL
SELECT a.COLUMN_NAME,
CASE WHEN a.COLUMN_NAME LIKE '%[_]_key' THEN a.COLUMN_NAME
ELSE REPLACE(a.COLUMN_NAME,'_',' ') END AS DISPLAY_NAME,
a.DATA_TYPE, COALESCE(a.CHARACTER_MAXIMUM_LENGTH, a.NUMERIC_PRECISION) AS SIZE,
CASE WHEN NUMERIC_SCALE IS NULL THEN 0
ELSE NUMERIC_SCALE END AS SCALE,
a.IS_NULLABLE AS NULLABLE,
CASE WHEN i.is_primary_key IS NOT NULL THEN 'YES'
ELSE 'NO' END AS PK,
#TEMP.SampleData
FROM PRESENTATION_PP.INFORMATION_SCHEMA.COLUMNS a
LEFT JOIN
sys.columns c ON a.COLUMN_NAME = c.name
LEFT JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
LEFT JOIN
#TEMP ON a.COLUMN_NAME COLLATE SQL_Latin1_General_CP1_CI_AI = #TEMP.SampleKey COLLATE SQL_Latin1_General_CP1_CI_AI
WHERE TABLE_NAME = #TableName AND c.object_id = OBJECT_ID(#TableName)
SELECT * FROM #TEMP
DROP TABLE #TEMP
END
Create the #Temp table first, and then INSERT INTO not Select ... Into #Temp
CREATE TABLE #TEMP (SampleKey nvarchar(MAX), SampleData nvarchar(MAX))
DECLARE #DynamicSQL NVARCHAR(MAX)
SET #DynamicSQL = N'
Insert Into #Temp
SELECT B.*
FROM (
SELECT * FROM ' + #Tablename + N' ORDER BY 1 DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY
) A
CROSS APPLY (
SELECT [Key] AS SampleKey
,Value AS SampleData
FROM OpenJson( (SELECT A.* FOR JSON Path, Without_Array_Wrapper,INCLUDE_NULL_VALUES ) )
) B
'
Exec(#DynamicSQL)
Select * from #Temp

T-SQL row count for each table with a WHERE

I'm using SQL Server and have the below query to retrieve the RowCount of all tables that begin with 'IN%'. This works fine.
However, within each 'IN...' table there is a column called 'ErrorFlg' - this can be 0 or 1.
How do I modify the below to also include a new column called 'NoOfErrors' that will count where the 'ErrorFlg = 1' in each table?
SELECT
ta.name AS TableName,
SUM(pa.rows) AS RowCnt
FROM
sys.tables AS ta
INNER JOIN
sys.partitions AS pa ON pa.object_id = ta.object_id
INNER JOIN
sys.schemas AS sc ON ta.schema_id = sc.schema_id
WHERE
(ta.is_ms_shipped = 0) AND (pa.index_id IN (1, 0))
AND (ta.name LIKE 'IN_%')
GROUP BY
sc.name, ta.name
ORDER BY
TableName, RowCnt DESC
Ideal output:
TableName RowCnt NoOfErrors
--------------------------------
IN_123 100 50
IN_4566 500 2
IN_ABC 250 125
As per #Lamu's suggestion, The will create a table variable with your results and then create and execute dynamic statements...
Declare #Tbl Table
(
TableName VarChar(50),
RowCnt Int
)
Insert Into #Tbl
SELECT
ta.name AS TableName,
SUM(pa.rows) AS RowCnt
FROM
sys.tables AS ta
INNER JOIN
sys.partitions AS pa ON pa.object_id = ta.object_id
INNER JOIN
sys.schemas AS sc ON ta.schema_id = sc.schema_id
WHERE
(ta.is_ms_shipped = 0) AND (pa.index_id IN (1, 0))
AND (ta.name LIKE 'IN_%')
GROUP BY
sc.name, ta.name
ORDER BY
TableName, RowCnt DESC
Declare #tblname VarChar(50)
Declare #rowcnt VarChar(10)
Declare #vsql VarChar(Max) = NULL
Declare c Cursor For Select TableName,RowCnt From #Tbl
Open c
Fetch Next From c Into #tblname, #rowcnt
WHILE ##FETCH_STATUS = 0
BEGIN
Set #vsql = 'Select ''' + #tblname +''' As Tbl,''' + #rowcnt + ''' As RowCnt, Count(*) As NoOfErrors From ' + #tblname + ' Where ErrorFlg = 1'
Exec(#vsql)
Set #vsql = NULL
Fetch Next From c Into #tblname, #rowcnt
END

How to select data from multiple tables where table name is value from a column of another table?

I have a table consists of table name, for example:
TableA
UID TableName CifKey ...
1 xxx 12345
1 yyy 12345
1 xxx 12345
2 zzz 45678
How can I select data from tables that having name same as the TableName column in Table A?
For example:
SELECT A.a, B.b
FROM TableA A
JOIN ' + #TableName + ' B ON A.Cifkey = B.Cifkey
WHERE A.uid = #uid AND A.cifkey = #cifkey
Thank you!
Dynamic SQL is the way to go:
DECLARE #uid INT = 1,
#cifkey INT = 12345
DECLARE #sql NVARCHAR(MAX) = ''
SELECT #sql = #sql +
'SELECT
A.a, B.b -- Replace with correct column names
FROM TableA A
JOIN ' + QUOTENAME(TableName) + ' B
ON A.Cifkey = B.Cifkey
WHERE
A.uid = #uid
AND A.cifkey = #cifkey
UNION ALL
'
FROM (
SELECT DISTINCT TableName FROM TableA WHERE UID = #uid AND cifkey = #cifkey
) t
IF #sql <> '' BEGIN
-- Remove the last UNION ALL
SELECT #sql = LEFT(#sql, LEN(#sql) - 11)
PRINT #sql
EXEC sp_executesql
#sql,
N'#uid INT, #cifkey INT',
#uid,
#cifkey
END
You will have to use a dyanmic query - something like this
DECLARE #tablename VARCHAR(50)
DECLARE #uid INT = 1
DECLARE #cifkey INT = 12345
SELECT #tablename = TableName FROM TableA WHERE uid = #uid AND cifkey = #cifkey
DECLARE #query VARCHAR(500)
SELECT #query = 'select A.a, B.b from TableA A JOIN ' + #tablename + ' B
ON A.Cifkey = B.Cifkey
WHERE A.uid = ' + CONVERT(VARCHAR(20),#uid) + ' and A.cifkey = ' + CONVERT(VARCHAR(20), #cifkey)
EXEC(#query)
If your join works,dynamic sql is the way you want to accomplish the task..
declare #tablename nvarchar(100)
select #tablename=tablename from yourtable where uid=#uid and cifkey=#cifkey
declare #sqlquery nvarchar(4000)
set #sqlquery='SELECT A.a, B.b FROM TableA A
JOIN ' + #TableName + ' B
ON A.Cifkey = B.Cifkey
WHERE A.uid = #uid and A.cifkey = #cifkey';
exec sp_executesql #sqlquery,
N'#uid int,#cifkey int',
#uid=10,#cifkey=100
In short, no, not as you are asking. You can, however, use dynamic SQL as in this answer to create a series of SELECT statements that could be merged with UNIONs to produce your desired results, like this:
SELECT DISTINCT 'SELECT A.a, B.b FROM TableA A
JOIN ' + TableName + ' B
ON A.Cifkey = B.Cifkey
WHERE A.uid = #uid and A.cifkey = #cifkey
UNION
'
FROM TableA
Just copy the results into the SQL editor, remove the UNION from the last item, and run the whole thing to get your results.
i have to say... this is a bit crazy
Note : I added a ID column to TableA as a primary key. This is required to uniquely identity the rows to differenciate multiple rows with same UID & Cifkey
-- Create the table
create table TableA
(
ID int identity,
UID int,
TableName varchar(5),
CifKey int,
a int
)
create table xxx
(
CifKey int,
b int
)
create table yyy
(
CifKey int,
b int
)
create table zzz
(
CifKey int,
b int
)
set nocount on
-- Insert some sample data
insert into TableA select 1, 'xxx', 12345, 1
insert into TableA select 1, 'yyy', 12345, 2
insert into TableA select 1, 'xxx', 12345, 3
insert into TableA select 2, 'zzz', 45678, 4
insert into xxx select 12345, 100
insert into yyy select 12345, 200
insert into zzz select 45678, 300
-- the Dynamic SQL query
declare #sql nvarchar(max)
select #sql = N'SELECT A.a, b = COALESCE('
select #sql = #sql +
+ N'B' + convert(varchar(10), ID) + '.b,'
from TableA
order by ID
select #sql = left(#sql, LEN(#sql) - 1) + ')' + char(13)
select #sql = #sql
+ N'FROM TableA A' + char(13)
; with cte as
(
select *, rn = convert(varchar(10), ID)
from TableA
)
select #sql = #sql
+ N'LEFT JOIN ' + quotename(TableName) + ' AS B' + rn + ' ' + char(13)
+ N'ON A.CifKey = B' + rn + '.CifKey' + char(13)
+ N'AND A.ID = ' + rn + char(13)
from cte
print #sql
exec sp_executesql #sql
set nocount off
-- clean up
drop table TableA
drop table xxx
drop table yyy
drop table zzz
-- The generated Query (print #sql)
SELECT A.a, b = COALESCE(B1.b,B2.b,B3.b,B4.b)
FROM TableA A
LEFT JOIN [xxx] AS B1
ON A.CifKey = B1.CifKey
AND A.ID = 1
LEFT JOIN [yyy] AS B2
ON A.CifKey = B2.CifKey
AND A.ID = 2
LEFT JOIN [xxx] AS B3
ON A.CifKey = B3.CifKey
AND A.ID = 3
LEFT JOIN [zzz] AS B4
ON A.CifKey = B4.CifKey
AND A.ID = 4

SQL server 2012 select row counts from a variable number of tables

I have the following query
select count(*) as row_count
, UN_PART
, 'ABC_PARAM_DETA' as TABLE_NAME
from ABC_PARAM_DETA
group by UN_PART
what I would like to do is extend this to use it from a select list rather than a single table as I have multiple tables with UN_PART eg
select count(*) as row_count
, UN_PART
, '#var_table' as TABLE_NAME
from (Select TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'UN_PART')
group by UN_PART
Anyone any ideas on how to achieve this
Try this
IF OBJECT_ID('tempdb..#Output') IS NOT NULL
DROP TABLE #Output
CREATE TABLE #Output
(ID INT IDENTITY(1, 1),
TableName NVARCHAR(MAX),
RowCnt INT)
INSERT INTO #Output (TableName)
Select C.TABLE_NAME from INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME = T.TABLE_NAME
WHERE COLUMN_NAME = 'UN_PART' AND T.TABLE_TYPE = 'BASE TABLE'
DECLARE #Step AS INT = 1
WHILE #Step <= (SELECT COUNT(*) FROM #Output) BEGIN
DECLARE #TableName NVARCHAR(MAX)
DECLARE #SQL NVARCHAR(MAX)
SELECT #TableName = TableName FROM #Output WHERE ID = #Step
SET #SQL = 'UPDATE #Output SET RowCnt = (SELECT COUNT(*) FROM ' + #TableName + ') WHERE TableName = ''' + #TableName + ''''
EXEC sys.sp_executesql #SQL
SET #Step = #Step + 1
END
SELECT * FROM #Output
DROP TABLE #Output
Haven't tested but I think this should work
Exec sp_MSforeachtable
#command1 ='select ''?'', un_part, count(1) from ? group by un_part'
,#whereand = ' and object_id in (select o.object_id from sys.objects o
inner join sys.columns c
on o.object_id = c.object_id
and c.name = ''UN_PART'')'

How to select column names from multiple tables in SQL server 2008 by avoiding certain columns which reoccur in all tables

I have a database that stores the complete details of the employees of a firm.
I need to select column names from multiple tables in the database which when executed would provide me the columns required to list specific details. So, I tried the following query which returns the columns of the specified table only.
SELECT TABLE_NAME,COLUMN_NAME
FROM mydatabase.INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME=N'TBLemppersonaldetails'
All the tables have a Column named 'EmployeeId' which can be considered as a primary key.
Now, how could i get all required columns from all the tables by avoiding certain columns such as Update Date,Mode that repeats in all the tables.
I would prefer using 'Inner Join' to join all the tables.
For example consider the tables below:
Table1 Table2
EmployeeId Name Address Mode EmployeeId Gender BloodGroup Mode
---------------------------------------- -------------------------------------------
001 abc No.9,vv 1 001 Male O+ve 1
street,
Considering the example above, I require the columns EmployeeId,Name,Address,Gender,BloodGroup to be listed after the execution of the query while excluding the column named 'Mode' from both the tables.
I request you to consider another scenario where the so called 'PrimaryKey' constraint doesn't exist for the 'EmployeeId' Column.
PS: I am using SQL Server 2008
You need to dynamically create a SQL statement and then run that command
Update 22.06.2013
IF OBJECT_ID('dbo.Table1') IS NOT NULL DROP TABLE dbo.Table1
CREATE TABLE dbo.Table1
(
EmployeeId int PRIMARY KEY,
Name varchar(100),
Address varchar(100),
Mode int
)
INSERT dbo.Table1
VALUES(1, 'abc', 'Address', 1)
IF OBJECT_ID('dbo.Table2') IS NOT NULL DROP TABLE dbo.Table2
CREATE TABLE dbo.Table2
(
EmployeeId int PRIMARY KEY,
Gender varchar(100),
BloodGroup varchar(100),
Mode int
)
INSERT dbo.Table2
VALUES(1, 'Male', 'O+ve', 1)
DECLARE #TablesWithAlias TABLE([schema] varchar(10), name varchar(20), alias varchar(10))
INSERT #TablesWithAlias
VALUES('dbo', 'Table1', 't1.'),
('dbo', 'Table2', 't2.')
DECLARE #dsql nvarchar(max)
SELECT #dsql = COALESCE(#dsql + ',', '') + MIN(twa.alias) + CASE WHEN o.IsPrimaryKey IS NOT NULL THEN c.name ELSE c.name END
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
OUTER APPLY (
SELECT CASE WHEN OBJECTPROPERTY(object_id(constraint_name), 'IsPrimaryKey') = 1 THEN 1 END AS IsPrimaryKey
FROM information_schema.key_column_usage k
WHERE s.name = k.table_schema AND t.name = k.table_name
AND c.name = k.COLUMN_NAME
) o
JOIN #TablesWithAlias twa ON s.name = twa.[schema] AND t.name = twa.name
GROUP BY c.column_id, c.name, o.IsPrimaryKey
HAVING COUNT(*) = 1 OR o.IsPrimaryKey IS NOT NULL
ORDER BY c.column_id
PRINT #dsql
--Your 'Inner Join' to join all the tables.
SET #dsql =
'SELECT ' + #dsql +
' FROM dbo.Table1 t1 JOIN dbo.Table2 t2 ON t1.EmployeeId = t2.EmployeeId '
PRINT #dsql
EXEC sp_executesql #dsql
Try this one -
DDL:
SET NOCOUNT ON;
IF OBJECT_ID (N'dbo.Table1') IS NOT NULL
DROP TABLE dbo.Table1
CREATE TABLE dbo.Table1
(
EmployeeId INT
, Name VARCHAR(30)
, [Address] VARCHAR(150)
, Mode INT
, Img IMAGE
, UpdateDate DATETIME
, IpAddress VARCHAR(20)
)
IF OBJECT_ID (N'dbo.Table2') IS NOT NULL
DROP TABLE dbo.Table2
CREATE TABLE dbo.Table2
(
EmployeeId INT
, Gender VARCHAR(6)
, BloodGroup VARCHAR(20)
, Mode INT
)
INSERT INTO dbo.Table1 (EmployeeId, Name, [Address], Mode, UpdateDate, IpAddress)
VALUES ('001', 'abc', 'No.9,vv street', 1,'06/04/2013 12:00:00','192.168.0.1')
INSERT INTO dbo.Table2 (EmployeeId, Gender, BloodGroup, Mode)
VALUES ('001', 'Male', 'O+ve', 1)
Query:
DECLARE #SQL NVARCHAR(MAX)
;WITH cte AS
(
SELECT
column_name = '[' + c.name + ']'
, table_name = '[' + s.name + '].[' + o.name + ']'
, [type_name] = t.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]
JOIN sys.types t WITH (NOLOCK) ON c.user_type_id = t.user_type_id
WHERE o.name IN ('Table1', 'Table2')
AND s.name = 'dbo'
AND o.[type] = 'U'
AND c.name NOT IN ('Mode', 'UpdateDate', 'IpAddress')
), 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, [type_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('
+ CASE
WHEN [type_name] = 'image' THEN 'CONVERT(VARBINARY(MAX), ' + cols.column_name + ')'
WHEN [type_name] = 'bit' THEN 'CAST(' + cols.column_name + ' AS CHAR(1))'
ELSE cols.column_name
END + ')')
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:
Address BloodGroup EmployeeId Gender Img Name
------------------ ------------ ----------- ------ -------- -------
No.9,vv street O+ve 1 Male NULL abc
Search your column name using this :
SELECT OBJECT_NAME (object_id ),*
FROM sys.columns
WHERE name LIKE 'ColumnName'