0

I would like to have the list of nodes set at the top of the script, then check if they are in the table. The following code does not throw errors, but the logic is not working. It does not print the message when one of the nodes in the list exists.

DECLARE @nodeId nvarchar(50)
SET @nodeId = 'SomeNodeID, SomeOtherNodeID'
IF EXISTS (SELECT NodeId FROM dbo.tblNodeMaster WHERE NodeId in (@nodeId))
BEGIN
    PRINT RTRIM(CONVERT(varchar(30), GETDATE())) + '  node exists.'
    RETURN
END

Using the following code without a variable it works fine. It will print the message when any node in the list exists.

IF EXISTS (SELECT NodeId FROM dbo.tblNodeMaster WHERE NodeId in ('SomeNodeID', 'SomeOtherNodeID'))
BEGIN
    PRINT RTRIM(CONVERT(varchar(30), GETDATE())) + '  node exists.'
    RETURN
END
3
  • 1
    You can't use in in that way with a string - it's a set operation, it doesn't parse the string. Commented Mar 31, 2021 at 19:04
  • 1
    Are you using MS SQL Server? (The above code is very product specific.) Commented Mar 31, 2021 at 19:04
  • Yes MS SQL Server Commented Mar 31, 2021 at 19:21

2 Answers 2

3

Instead of using a string, you could use a table variable

    Declare @NodeId table (NodeId varchar(30))
    insert into @NodeId
    select 'SomeNodeID' union all select 'SomeOtherNodeID'
    
    IF EXISTS (SELECT * FROM dbo.tblNodeMaster WHERE NodeId in (select NodeId from @nodeId))
...
Sign up to request clarification or add additional context in comments.

3 Comments

So, I actually have the NodeIDs in a data file. So I just loaded them into a temp table and used that. Thanks for help!
Ever heard of values('SomeNodeID', 'SomeOtherNodeID')
Haha yes - force of habbit I guess.
3
DECLARE @nodeId nvarchar(50) = 'SomeNodeID,SomeOtherNodeID'
IF EXISTS (SELECT * FROM dbo.tblNodeMaster WHERE NodeId IN (SELECT LTRIM(value) FROM STRING_SPLIT(@nodeId, ','))
BEGIN
    PRINT RTRIM(CONVERT(varchar(30), GETDATE())) + '  node exists.'
    RETURN
END

You can use STRING_SPLIT as a sub-query to the IN operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.