Reputation: 39
when using doing an insert statement with a sql statment do the following
Insert tablename (column1, column2)
select statement
Is there a way to format an if statement so that if a varible is set you would run the insert statement. This is what I have but it shows the end statement in error so i need help
if @runthis=1
begin
insert tablename (column1, column2)
end
select column1, column2
Upvotes: 1
Views: 52
Reputation: 31785
If you use BEGIN after the IF, you must also include an END after the INSERT, and NOT in the middle of the INSERT..SELECT.
Like this:
if @runthis=1
begin
insert tablename (column1, column2) select column1, column2
end
Technically, you could avoid using an ELSE as you describe in your comment by using dynamic SQL like this:
DECLARE @SQL varchar(max) = '';
if @runthis=1
begin
SET @SQL = 'insert tablename (column1, column2) ';
end
SET @SQL = @SQL + 'select column1, column2';
EXECUTE (@SQL);
Personally, I would use an ELSE
instead though.
Upvotes: 2
Reputation: 93734
The statements used inside a IF
condition should be valid. The correct way to use IF
condition is pointed out in other answer.
Here is another way
insert tablename (column1, column2)
select column1, column2
Where @runthis=1
Upvotes: 2