Hi experts. I have this SQL block:
Insert into dbo.Tables1
([ServerInstance]
,[DatabaseName]
,[Schema]
,[TableName]
,[ColName]
,[ColumnName]
,[ColumnValue]
,[DateCollected])
SELECT TOP 1
@@SERVERNAME,DB_Name(), null,null,null, ColumnName, ColumnValue, getDate() FROM #Results
ORDER BY ColumnName
It works but it only inserts 1 row. I have many different values in ColumnName. And ColumnName contains duplicate values.
**How can I select only 1 row for each ColumnName?
SELECT TOP 1 WITH TIES
@@SERVERNAME
, DB_Name()
, null
, null
, null
, ColumnName
, ColumnValue
, getDate()
FROM #Results
ORDER BY
ROW_NUMBER() OVER(PARTITION BY @@servername, db_name() ORDER BY ColumnName);
Jeff, that's close to what I need. But it returns only 1 row per resultset. The #Results table contains many tables and column names (and there are duplicates by design)
For Example: ColumnName can contain
dbo.Table1.Column1
dbo.Table1.Column1
dbo.Table1.Column2
I need to select 2 rows in the example above:
dbo.Table1.Column1 and
dbo.Table1.Column2
Without seeing actual data - and sample results I am not sure if that will work. If partitioning by the column name works then great, but you have many other columns available that could be utilized - for example you could include the schema, table and ColName in the partition.
It also looks like ColumnName is actually a concatenation of those 3 columns...
select @@servername as servername,
DB_Name() as dbName,
t.name,
c.name,
getDate()
from sys.tables t
join sys.columns c on t.object_id = c.object_id
ORDER BY
ROW_NUMBER()
OVER(PARTITION BY @@servername, db_name() ORDER BY c.name);