Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute store procedure for another DB?

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 result in anything. Here is the stored procedure:

CREATE PROCEDURE [dbo].[usp_TrimAndLowerCaseVarcharFields]
(
    @Database VARCHAR(200),
    @TableSchema VARCHAR(200),
    @TableName VARCHAR(200)
)
AS
BEGIN
    DECLARE @sSql VARCHAR(MAX)

    SET @Database = '[' + @Database + ']'
    SET @sSql = ''

    -- Create first part of a statement to update all columns that have type varchar
    SELECT @sSql = @sSql + COLUMN_NAME + ' = LOWER(RTRIM(' + COLUMN_NAME + ')), ' 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE DATA_TYPE = 'varchar'
    AND TABLE_CATALOG = @Database
    AND TABLE_SCHEMA = @TableSchema
    AND TABLE_NAME = @TableName

    SET @sSql = 'UPDATE ' + @Database + '.' + @TableSchema + '.' + @TableName + ' SET ' + @sSql

    -- Delete last two symbols (', ')
    SET @sSql = LEFT(@sSql, LEN(@sSql) - 1)

    EXEC(@sSql)
END

Please, advice what I have to do to execute it on [OtherDB].[TargetTable].

like image 255
Oleg Sakharov Avatar asked Nov 21 '11 05:11

Oleg Sakharov


2 Answers

You can fully qualify both tables and stored procedures. In other words you can do this:

UPDATE [OtherDB].[Schema].[targetTable] SET ...

It appears you are doing this in your proc already.

You can also EXEC a stored procedure using the Fully Qualified name - e.g.

EXEC [OtherDB].[dbo].[usp_TrimAndLowerCaseVarcharFields]

Honestly, your proc looks fine, are you receiving any error messages? If so please post them. Also, make sure your user has access to the other DB.

like image 145
Code Magician Avatar answered Nov 14 '22 23:11

Code Magician


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.

like image 40
Elias Hossain Avatar answered Nov 14 '22 21:11

Elias Hossain