0

I want to insert in the table only if I do not have the specific column it is a track table with different titles and I want to add different titles with one procedure I did the try catch and I have problem in my where not exists condition, I don't know where to put the values term:

BEGIN TRANSACTION [Tran1]
BEGIN TRY

INSERT INTO  [s15guest59].[dbo].[track](track_topic)
values(@par1)
   WHERE NOT EXISTS (SELECT track_topic FROM [track]
                     WHERE track_topic=@par1)
COMMIT TRANSACTION [Tran1]
END TRY
BEGIN CATCH
  ROLLBACK TRANSACTION [Tran1]
END CATCH  

GO

I don't know what to write in the middle for it to work

Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "@par1".

Nickool
  • 3,662
  • 10
  • 42
  • 72

1 Answers1

0

if you planing to use stored procedure you can create stored procedure:

    CREATE PROCEDURE spAddTrack 
@trackName VARCHAR(MAX)

AS

If not exists( Select * from [s15guest59].[dbo].[track] where track_topic=@trackName)
BEGIN
    INSERT INTO  [s15guest59].[dbo].[track](track_topic) VALUES (@trackName)
END

thank execute it with:

EXEC spAddTrack 'this is new track'
Matija Gluhak
  • 260
  • 2
  • 13
  • but how do you execute this .. is it stored procedure ? – Matija Gluhak Apr 27 '15 at 20:20
  • thank you now can you tell me what was wrong with mine? – Nickool Apr 27 '15 at 20:28
  • what about the transaction, what if I had the transaction what should I write then? – Nickool Apr 27 '15 at 20:29
  • first you have to create Stored procedure in SQL server with command Create procedure _name_ and you specify input paramters in your case @trackName .. and than you can use that parameter in Stored procedure body inside SQL statments like in your case "where" statment. When you strore SP, you can execute it with Exec SP_name + parameters – Matija Gluhak Apr 27 '15 at 20:31
  • your transaction here is not needed since you do all of this in one batch anyway so there is nothing to rollback, Transactions are used when you have multiple inserts, updates and/or deletes so if one of them fail you can roll back all or some parts. Read more about transactions at [link](https://msdn.microsoft.com/en-us/library/ms188929.aspx) – Matija Gluhak Apr 27 '15 at 20:34