Andrew Alderson
Andrew Alderson

Reputation: 1018

T-SQL error with subquery

I need help with a T-SQL select statement. It is for SQL Server 2014

I have 3 tables.

I need to check the Jobs table to find out if there are any jobs scheduled for a CourseEnrollment where its Course has had the AllowReEnroll flag turned off but the ReEnrollAutomatically flag is on.

This is what I have been trying

SELECT
    *
FROM
    Jobs
WHERE
    Arguments LIKE '%' + (
        SELECT
            CONVERT( nvarchar(50), Id )
        FROM
            CourseEnrollments
        WHERE
            CourseId IN (
                SELECT
                    Id
                FROM
                    Courses
                WHERE
                    AllowReEnroll = 0
                    AND
                    ReEnrollAutomatically = 1
            )
    ) +'%'

I can query the CourseEnrollments table to get all of the ids of CourseEnrollments where the Course's flags are set accordingly with

SELECT
    *
FROM
    CourseEnrollments
WHERE
    CourseId IN (
        SELECT
            Id
        FROM
            Courses
        WHERE
            AllowReEnroll = 0
            AND
            ReEnrollAutomatically = 1
    )

but when I try to use that as a subquery I get the following error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.'

Not being a dba I have spent the day trying to figure this out. How do I write this query?

Upvotes: 1

Views: 89

Answers (1)

Pரதீப்
Pரதீப்

Reputation: 93754

Use EXISTS/Join to do this

Using EXISTS

SELECT *
FROM   Jobs j
WHERE  EXISTS (SELECT 1
               FROM   CourseEnrollments c
               WHERE  c.CourseId IN (SELECT Id
                                     FROM   Courses
                                     WHERE  AllowReEnroll = 0
                                            AND ReEnrollAutomatically = 1)
                      AND j.Arguments LIKE '%' + CONVERT(NVARCHAR(50), c.Id) + '%') 

Using INNER JOIN

SELECT j.*
FROM   Jobs j
       JOIN CourseEnrollments c
         ON j.Arguments LIKE '%' + CONVERT(NVARCHAR(50), c.Id) + '%'
WHERE  c.CourseId IN (SELECT Id
                      FROM   Courses
                      WHERE  AllowReEnroll = 0
                             AND ReEnrollAutomatically = 1) 

Upvotes: 3

Related Questions