sqlsql-server-2012validating

Validate a value in sql using and if exists statement?


I am still pretty new to everything and now I am trying to validate my input SQL.

My powershell script allows me to se some variables which I want to enter in a selected database. What I need is a check if the entry already exists or not. And if it exists my script shall stop.

Script part :

if exists(select * from [DB1].dbo.[table1]
            where Name = '$variable1')

    "stop script but how?"

else

    insert into ......

So I need something which replaces "stop script but how?" somehow :)


Solution

  • Why do you need to "stop" the script? Reverse your logic - if the thing doesn't exist, only then do the rest of the stuff.

    IF NOT EXISTS (SELECT ...)
    BEGIN
        -- do all the things
    END