SQL Server -- Loop through each column in every table?
I have a business need I haven't seen in 10 or 15 years, so please excuse the dino-code I will use to illustrate what I'm trying to do. I know there is a way to do something like this in SQL Server, it's just been too darned long for me.
Back in the MS DAO days I would use something like this to iterate through every field in every table. Ahh... Memories...
Dim dbs as DAO.Database
Dim tdf as DAO.TableDef
Dim fld as DAO.Field
For Each tdf in dbs.TableDefs
For Each fld in tdf.Fields
'Do whatever to every field in every table here.
Next
Next
Can any开发者_开发百科one give me a SQL-Server equivalent?
EDIT: Inside whatever loop structure I can set up, I also need to reference the table name and field name (ie: tdf.Name and fld.Name). Thanks!!!
EDIT 2: FYI I'll be building SELECT statements from the logic.
This will get you every column in its own row for the current database:
SELECT s.name SchemaName, t.name TableName, c.name ColumnName
FROM sys.columns c INNER JOIN
sys.tables t ON c.object_id = t.object_id INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
;
You could iterate through that using any number of data access technologies (ADO .NET, LINQ, etc.).
精彩评论