So I made a procedure that makes a dynamic view using dynamic SQL, but I used two sql executions: One for the if clause and one for the else, it should be possible to put it all under one SQL string or am i wrong? Because I tried it and get an error over and over again. Im not the best in writing dynamic sql, so it is probably my mistake or cant it be done and im losing my time on trying to do this?
create procedure test_view
(@table_name varchar(30))
as
BEGIN
declare@ sqlQuery varchar(100)
if exists(select 1 from sp_iqview('v_anon_' + @table_name) where view_name = 'v_anon_' + @table_name)
begin
set@ sqlQuery = ('drop view ' + 'v_anon_' + @table_name)
EXECUTE(@sqlQuery)
end
else
begin
set@ sqlQuery = ('CREATE VIEW ' + 'v_anon_' + @table_name + ' AS SeLECT * FROM ' + @table_name)
EXECUTE(@sqlQuery)
select@ sqlQuery
end
END
try this query.... Here else statement is not required.... if the object exists, it will drop in the first step itself. If not, it create new one...
create procedure test_view
(@table_name varchar(30))
as
BEGIN
declare @DropQuery varchar(100)
declare @CreateQuery varchar(100)
IF EXISTS(select 1 from sp_iqview('v_anon_' + @table_name) where view_name = 'v_anon_' + @table_name)
BEGIN
SET @DropQuery= 'drop view v_anon_' + @table_name
EXEC sp_executesql @DropQuery
END
SET @CreateQuery = 'CREATE VIEW v_anon_' + @table_name + ' AS SeLECT * FROM ' + @table_name
EXEC sp_executesql @CreateQuery
SELECT @CreateQuery
END