I need to store a query as a stored procedure in SQL Server.
I need also to pass parameters which define tablenames and column names.
This is the query I owuld like to have, I tried to store it in a string and then EXECUTE
it but without success, ho can I solve this?
CREATE PROCEDURE sp_selectAllParents @id int, @tableid varchar(30), @tablename varchar(30)
AS BEGIN
SET NOCOUNT ON;
WITH ct AS (
SELECT * FROM @tablename t WHERE @tableid = @id
UNION ALL
SELECT t.* FROM @tablename t JOIN ct ON t.parentId = ct.@tableid
)
SELECT * FROM @tablename t WHERE @tableid NOT IN (SELECT @tableid FROM ct)
END
EDIT: my attempt was:
DECLARE @sql varchar(255)
SET @sql = 'WITH ct AS (SELECT * FROM @tablename t WHERE @tableid = @id UNION ALL SELECT t.* FROM @tablename t JOIN ct ON t.parentId = ct.@tableid) SELECT * FROM @tablename t WHERE @tableid NOT IN (SELECT @tableid FROM ct)'
EXEC(@sql)