Sample Header Ad - 728x90

Need to modify Stored Procedure to create table in another database

0 votes
1 answer
157 views
We have a SQL database that is a secondary database or should I say a secondary replica in an AlwaysOn Availabiltity Group. As a result, the database is always a read-only database and therefore I can't execute the stored procedure below because the stored procedure attempts to create a new table .. basically I get hte error message: Failed to update database xxxxxx because the database is read-only. It was suggested that a workaround would be to modify the procedure to SELECT ... INTO a table on a different database (that's not read-only / not part of an AlwaysOn Availability Group) that lives in the same server. E.g: INTO SomeOtherDatabase.' + QUOTENAME(@Domain) + '.' + QUOTENAME(@DeltaTable) + ' Can someone please take a look at my code and help modify the code. I tried the following: INTO tempdb.dbo.@DeltaTable' + QUOTENAME(@Domain) + '.' + QUOTENAME(@DeltaTable) + ' The above didn't work. The full procedure is as follows: CREATE PROCEDURE dbo.GenerateDeltaTable @Domain VARCHAR(100), @TableName VARCHAR(100), @DeltaTable VARCHAR(100) AS BEGIN SET NOCOUNT ON; DECLARE @sql NVARCHAR(MAX); -- Construct dynamic SQL for dropping and creating the target table SET @sql = ' IF OBJECT_ID(''' + QUOTENAME(@Domain) + '.' + QUOTENAME(@DeltaTable) + ''', ''U'') IS NOT NULL DROP TABLE ' + QUOTENAME(@Domain) + '.' + QUOTENAME(@DeltaTable) + '; SELECT T.*, LOWER(CONVERT(VARCHAR(64), HASHBYTES(''SHA2_256'', (SELECT T.* FOR JSON PATH, WITHOUT_ARRAY_WRAPPER, INCLUDE_NULL_VALUES)), 2)) AS signature INTO ' + QUOTENAME(@Domain) + '.' + QUOTENAME(@DeltaTable) + ' FROM ' + QUOTENAME(@Domain) + '.' + QUOTENAME(@TableName) + ' AS T;'; -- Execute the constructed SQL EXEC sp_executesql @sql; END; Any thoughts on how to create the table from the stored procedure to another database
Asked by Patterson (123 rep)
Jan 19, 2025, 11:59 AM
Last activity: Jan 19, 2025, 03:03 PM