• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 29
  • Last Modified:

Dynamically build a UNION ALL


In a SQL Server database there are multiple tables. I want to search for a certain string-value accross these tables using a Stored Procedure. The result-set from each table will be exactly the same and is currently combined using "UNION ALL".
Depending on the authorization of a user (in my Delphi app) I only want to select records from certain tables. So I was thinking about using a few parameters to pass that information.
If a user is not authorized for any of the tables the resultset will be empty.

      @SearchString  nvarchar(255),
      @AllowTable1  bit,
      @AllowTable2  bit,
      @AllowTable3  bit
  -- Based on parameter @AllowTable1 I want to add values from Table1 to the selection (or not).
  SELECT MyID1 AS ID, MyNvarcharField1 AS FoundString, 'Table1' AS Table 
  FROM Table1
  WHERE MyNvarcharField1 LIKE '%' + @SearchString + '%'
  -- Based on parameter @AllowTable2 I want to add values from Table2 to the selection (or not).
  SELECT MyID2 AS ID, MyNvarcharField2 AS FoundString, 'Table2' AS Table 
  FROM Table2
  WHERE MyNvarcharField2 LIKE '%' + @SearchString + '%'
  -- Based on parameter @AllowTable3 I want to add values from Table3 to the selection (or not).
  SELECT MyID3 AS ID, MyNvarcharField3 AS FoundString, 'Table3' AS Table 
  FROM Table3
  WHERE MyNvarcharField3 LIKE '%' + @SearchString + '%'

Open in new window

What would be the right way to accomplish this?
Any different approach is perfectly fine for me too.
Stef Merlijn
Stef Merlijn
1 Solution
Add an appropriate predicate to each where clause e.g. for table1

 ... And @allowtabe1 = true

Not sure about bit variables I think you can use true.
Stef MerlijnDeveloperAuthor Commented:
Perfect and so simple. Thanks!

For certain you can use (1=True, 0=False):
 ... And @allowtabe1 = 1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now