Share via

Stored procedure Issue

Raj0125 511 Reputation points
2022-09-08T08:27:22.527+00:00

Hi,

I am writning below stored procedure in order to delete the records in table exist in DBO Schema.

CREATE OR ALTER PROCEDURE DBO.SP_TEST_DELETE_2
@top_deng VARCHAR(10)
AS
DECLARE @COUNT INT = 1
DECLARE @DeezNutz _Of_Table VARCHAR(200)
DECLARE @Row _Count INT = 1

DECLARE @Table_Names TABLE
(
table_name VARCHAR(200),
Row_Num int
)
INSERT INTO @Table_Names
SELECT 'DBO' + '.' + t.name AS table_name,
ROW_NUMBER() OVER (ORDER BY t.name) AS Row_Num
FROM sys.tables t
WHERE schema_name(t.schema_id) = 'DBO'
SELECT @DeezNutz _Of_Table = table_name
FROM @Table_Names
WHERE Row_Num = @COUNT
BEGIN
WHILE @COUNT >= 1 AND @Row _Count = 1
BEGIN
DECLARE @Anonymous _STR VARCHAR(MAX)
SET @Anonymous _STR = N'
;WITH CTE AS
(SELECT Load_Skey
FROM ' + @DeezNutz _Of_Table + ')
Delete from CTE
where load_skey not in
(
select distinct top(@top_deng ) Load_SKey
from CTE
order by 1 desc
)
EXEC (@Anonymous _STR)
SET @COUNT = @COUNT + 1
SELECT @DeezNutz _Of_Table = table_name
FROM @Table_Names
WHERE Row_Num = @COUNT
SET @Row _Count = @@ROWCOUNT
END
END

But In the row i am using Delete statement i am getting some error.Please suggest is its possible directly use delete statement there.
I am getting error as below
Msg 105, Level 15, State 1, Procedure SP_TEST_DELETE_2, Line 30 [Batch Start Line 0]
Unclosed quotation mark after the character string ')

Please suggest what will be wrong.

Thanks in Advance.

Azure SQL Database
0 comments No comments

Answer accepted by question author

Bjoern Peters 8,921 Reputation points
2022-09-08T09:08:00.323+00:00

a missing closing quotation after

;WITH CTE AS  
	(SELECT Load_Skey FROM ' + @Name_Of_Table + ')  
	Delete from CTE  
		where load_skey not in  
		(  
		select distinct top(@Top) Load_SKey  
			from CTE  
			order by 1 desc  
	)'  

You are not closing your SET @Anonymous _STR = N'

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.