I need to get the table column names that are in another database. A script is running for the active database, but I need to run it with a different database in the same server instance:
SELECT @ColumnList =
CASE
WHEN @ColumnList IS NULL THEN name
WHEN @ColumnList IS NOT NULL THEN @ColumnList + ',' + name
END
FROM sys.columns
WHERE object_id = Object_Id(@TableName);
Here's the problem ... the database is unknown at compile time. It is passed to the stored procedure at runtime. Therefore, I see no alternative but to use dynamic sql. I used to try to use a Use [DBName]script in dynamic sql, but I always ran into problems until I realized that I could do this:
SET @SQL = 'SELECT Foo FROM Bar'
SET @sp_executesql = quotename(@DatabaseName) + '..sp_executesql'
EXECUTE @sp_executesql @SQL
But it’s hard for me to figure out how to do this with the script I mentioned above. My first attempt looked like this:
DECLARE @ColumnList nvarchar(max),
@SQL nvarchar(max),
@sp_executesql nvarchar(max) = quotename(@DatabaseName) + '..sp_executesql';
SET @SQL =
'SELECT @ColumnList =
CASE
WHEN @ColumnList IS NULL THEN name
WHEN @ColumnList IS NOT NULL THEN @ColumnList + '','' + name
END
FROM sys.columns
WHERE object_id = Object_Id(@TableName);'
EXECUTE @sp_executesql @SQL,
N'@ColumnList = nvarchar(max) OUT, @TableName = sysname',
@ColumnList, @TableName
, @ColumnList . ?