Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Help with syntax on using variables

Author  Topic 

stuckne1
Starting Member

22 Posts

Posted - 2010-01-14 : 15:05:00
Hi, i'm trying to check to see whether something exists or not before I allow the stored procedure to add the entry.

ALTER PROCEDURE [dbo].[P_sp_UpdateCompletedModules]
-- Add the parameters for the stored procedure here
@ParkID int,
@module_id int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
var @counter as int
SELECT * FROM tblCompleted
join tblBPIModules on tblCompleted.module_id = tblBPIModules.id
WHERE user_id = @ParkID AND module_id = @module_id


IF @counter = 0
BEGIN
INSERT INTO tblCompleted(user_id, module_id)
VALUES(@ParkID, @module_id)
END
END

DP978
Constraint Violating Yak Guru

269 Posts

Posted - 2010-01-14 : 15:16:59
I would use this to get you started...

http://www.sqlteam.com/article/using-exists
Another good resource...
http://weblogs.sqlteam.com/mladenp/archive/2007/07/30/60273.aspx

So...

IF NOT Exists(SELECT * FROM tblCompleted
join tblBPIModules on tblCompleted.module_id = tblBPIModules.id
WHERE user_id = @ParkID AND module_id = @module_id)
Begin
INSERT INTO tblCompleted(user_id, module_id)
VALUES(@ParkID, @module_id)
END

Something along those lines...



Go to Top of Page

stuckne1
Starting Member

22 Posts

Posted - 2010-01-14 : 15:24:42
I will read those articles. Thank you very much!
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-01-14 : 15:46:45
Instead of "var" in your code, you need DECLARE. Please consult Books Online for more information.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

DP978
Constraint Violating Yak Guru

269 Posts

Posted - 2010-01-14 : 15:49:51
Sorry tara, i would of informed the same, but in my example I removed counter altogether.

But she is quite right, no var in sql.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-01-14 : 18:27:48
I only mentioned the variable correction with DECLARE in case variables are needed in future stored procedure code. Obviously they aren't needed in these example.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page
   

- Advertisement -