crux sql if statement problem
Work on ms-server 2005.In my stored procedure i need to use if statement ,I already try to write but i fail ,My syntax is bellow :
Create Proc开发者_如何转开发edure TestProcedure
@Type int
as
SELECT * INTO #temp1 FROM (
if @Type =0
select * from dbo.Manifest
else
select * from dbo.DischargePort
) as b
After execute the above syntax show me error message ,Message is
Msg 156, Level 15, State 1, Procedure TestProcedure, Line 8
Incorrect syntax near the keyword 'if'.
Msg 170, Level 15, State 1, Procedure TestProcedure, Line 14
Line 14: Incorrect syntax near ')'.
How to fix the problem,Thanks in advance.
EDIT Ok, so you can't actually insert into #temptable twice because the compiler does not recocgnize that it uses an if statement, the closest workaround was the following:
IF @Type = 0
BEGIN
exec select * into #temp from dbo.Manifest
END
ELSE
BEGIN
select * into #temp from dbo.DischargePort
END
VERSION 2
DECLARE @Type int = 0
IF @Type = 0
exec ('select * into ##temp from dbo.Manifest')
ELSE
exec ('select * into ##temp from dbo.DischargePort')
SELECT * FROM ##temp
And then remember to drop the table at the end
IF (SELECT object_id('TempDB..##temp')) IS NOT NULL
BEGIN
DROP TABLE ##temp
END
And then you would access ##temp like a normal table. Remember that if you want to add parameters to the dynamic sql use sp_exceutesql to avoid sql injection
You remind to drop #temp at the end. Before table creation,you should check if #temp already exists.
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp (id int)
精彩评论