How to create a function/ view/ trigger/ procedure inside a procedure?

976    Asked by JamesBuckland in SQL Server , Asked on Jan 11, 2020
Answered by Rachit Gupta

Creating/updating tables is allowed in the procedure directly, however creating a view/ trigger/ procedure is not allowed directly. So we can write dynamic queries to perform such tasks, in this we make a sql command (procedure/view/function/trigger details) in the variable and then execute it.

create proc usp_Test_Multiple_Proc_Create

  as

  begin

  if not exists( select 1 from sys.objects where type='P' and NAME='usp_Test_Multiple_task_1')

  begin

declare @sql nvarchar(300)

set @sql=' create proc usp_Test_Multiple_task_1

  as

  begin

  select 1

  end

'

exec sp_executesql @sql

print 'Proc created'

end

else

 print 'Proc already exists'

end

Now executing the procedure:

exec usp_Test_Multiple_Proc_Create

This will create the procedure and get the output as 'Proc created'

On second time execution the procedure:

exec usp_Test_Multiple_Proc_Create

We will get the output as 'Proc already exists'

This kind of requirement comes when we have to create a procedure with some user input/values and then execute it and drop it after use.



Your Answer

Interviews

Parent Categories