patternsqlMinor
Pull data from sys.columns in a different database
Viewed 0 times
pullcolumnsdatabasedifferentsysfromdata
Problem
I am running the following on one instance on the server:
Everything works great.
I would like to run the same statement but point it to another database on the server.
databaseName.dbo.tablename
I've tried the following (and other variations), but it does not work.
Is there a way to get the column information on one database from another?
Code:
Is there a way to do this dynamically? If I had a
SELECT c.*
FROM sys.columns c
WHERE c.object_id = OBJECT_ID(@tablename);Everything works great.
I would like to run the same statement but point it to another database on the server.
databaseName.dbo.tablename
I've tried the following (and other variations), but it does not work.
SELECT c.*
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('databaseName.dbo.tablename');Is there a way to get the column information on one database from another?
Code:
SELECT @SQL = @SQL + 'INSERT INTO myTable
(ColumnName,ColumnValue,SID,SName,RID,RName)
VALUES (''' + QUOTENAME(c.name) + ''',NULL,0,NULL,0,NULL);'
FROM sys.columns c
WHERE c.object_id = OBJECT_ID(@tablename);
EXEC(@SQL);Is there a way to do this dynamically? If I had a
@DBName parameter that I was passing in.Solution
Add in the database you are looking to query from in front of the sys.columns.
SELECT c.*
FROM .sys.columns c
WHERE c.object_id = OBJECT_ID(@tablename);Code Snippets
SELECT c.*
FROM <other database name>.sys.columns c
WHERE c.object_id = OBJECT_ID(@tablename);Context
StackExchange Database Administrators Q#151359, answer score: 7
Revisions (0)
No revisions yet.