Andrea Morgera
Andrea Morgera

Reputation: 1

SQL Subqueries concatenation issue

I have a simple subquery that works fine

SELECT id, Name, subset
 , (select count (1) from anotherTable where qid = someTable.id )
FROM someTable

the value "subset" is a string ie: "and (PreQ1 like '%A%') and ( PreQ2 like '%A%' or PreQ2 like '%C%')"

And so I'd like to ConCatenate the subquery with the value subset like this:

SELECT id, Name, subset
 , exec  ( 'select count (1) from anotherTable where qid = someTable.id ' + subset)
 FROM someTable

.. but get a "Conversion failed" error

Upvotes: 0

Views: 61

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270371

Is this what you want?

SELECT s.id, s.Name, s.subset,
       (select cast(count(1) as varchar(255)) + s.subset
        from anotherTable a
        where a.qid = s.id
       )
FROM someTable s;

This does the concatenation within the subquery. You can also put the + s.subset outside the subquery.

Also note that table aliases make the query easier to write and to read.

Upvotes: 1

Related Questions