How to execute store procedure for another DB?

后端 未结 3 403
野趣味
野趣味 2021-01-18 02:15

I have a stored procedure that should be able to be executed on any table of any database on my MS Sql Server. Most of the combination of EXEC and USE statements didn\'t res

3条回答
  •  忘掉有多难
    2021-01-18 02:54

    The table name in the query you used is wrong, it is looking up into same database, but you do need to look up from different database. So the query will be as below:

    SELECT @sSql = @sSql + COLUMN_NAME + ' = LOWER(RTRIM(' + COLUMN_NAME + ')), ' 
    FROM [TargetDB].INFORMATION_SCHEMA.COLUMNS 
    WHERE DATA_TYPE = 'varchar'
    AND TABLE_CATALOG = @Database
    AND TABLE_SCHEMA = @TableSchema
    AND TABLE_NAME = @TableName
    
    -- [TargetDB] = @Database
    

    The TargetDB will be same as your passing database (@Database)

    If you want to use [TargetDB] dynamically then you need to generate sql(@sSql) and the execute the sql string.

提交回复
热议问题