tags:

views:

107

answers:

3

I'm trying to write a Stored Procedure this is what I have so far

Create procedure sp_Create_order
@P_nafn varchar(50),
@P_fj int,
@P_sótt datetime,
@F_kt varchar(10),
@V_nr int,
@L_id int

as 
begin
    set nocount on

if exists(
   select * from Lotur
   where L_id=@L_id and
   @P_sótt between L_hefst and L_pfrest
)
INSERT INTO Pantar(P_nafn, P_fj, P_sótt, F_kt, V_nr, L_id) 
VALUES (@P_nafn, @P_fj, @P_sótt, @F_kt, @V_nr, @L_id)
end

but I am getting these errors

Msg 102, Level 15, State 1, Procedure sp_Create_order, Line 14 Incorrect syntax near ' '.

Msg 102, Level 15, State 1, Procedure sp_Create_order, Line 15 Incorrect syntax near ' '.

on these lines

select * from Lotur
where L_id=@L_id

and

@P_sótt, L_hefst and L_pfrest are all dates and I am tryng to put a condition on saying that nothing should be Inserted unless @P_sótt is equal to or between L_hefst and L_pfrest

+1  A: 
  • Please use meaningful names for your variables
  • Do not create sp for every thing like the one above
  • Modify the query to have SELECT L_ID NOT SELECT *
  • As for the error, probably you have mistyped something
Albert
Does select * really matter if it's inside an exists?
Jeffrey Hantin
The procedure as is compiles and ran for me under SQL Server 2005, it's possibly some other strange problem.
Nick Josevski
Not sure Jeffrey...query optimizer maybe be able to optimize it, but still there's no reason to "select *"
Albert
I'd disagree on your 2nd point -- we create stored procs for ALL database access. No direct SELECT/INSERT/UPDATE/DELETEs allowed.
Joe
There's a huge debate on the 2nd point. My preference is to not use sp for every trivial thing.
Albert
A: 

First of all, I wouldn't recommend prefixing your Stored Procedure with sp_. Performance is at least one reason why it's a bad idea.

Your stored procedure compiled ok for me. Another recommendation would be to use

if exists (
   select 1 
   from 
       Lotur
   where 
       L_id= @L_id 
       and @P_sótt between L_hefst and L_pfrest
)

as opposed to SELECT *. Did you get the error when compiling or trying to use it?

EDIT:

In response to your post about raising errors, you might want to look at RAISERROR. Here is an example of how to use it in Stored procedures

Russ Cam
Is this still an issue with SQL 2005/2008? That article you referenced was from 2001.
Simon Hartcher
IMHO, you should never use sp_ at the start of your own stored procedures. SQL Server will always look in master first
Russ Cam
Run the profiler and try it :) I found it to be the case in 2005 - I don't know about 2008 but I suspect the same, considering MS advise against the practice
Russ Cam
A: 

Ok thanks I've got it working now do you have any ideas on how to throw an error if @P_sótt is not between L_hefst and L_pfrest

Ok I got it working like it should now thanks