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].
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.