Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use `exec` in a where clause?

Tags:

sql-server

I am trying to query an instance of SQL Server to give me a list of databases that contain a table of a specific name. This is what I have so far...

select name
from master..sysdatabases
where (exec('use ' + name + '; select 1 from information_schema.tables 
  where table_name = ''TheTableName'';')) = 1;

But I get the following error messages

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'exec'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'name'.

What is the correct syntax to use call exec() in a where clause? Or is there another way to do what I'm trying to do?

like image 386
Nick Strupat Avatar asked Apr 16 '12 15:04

Nick Strupat


People also ask

Which operator Cannot be used in WHERE clause?

Join, subquery and aggregate functions are not supported.

Can we use EXEC in SELECT statement?

Stored procedures are typically executed with an EXEC statement. However, you can execute a stored procedure implicitly from within a SELECT statement, provided that the stored procedure returns a result set.

Can we use or operator in WHERE clause?

The WHERE clause can be combined with AND , OR , and NOT operators.

Which conditions can we use with WHERE clause?

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.


2 Answers

No, you cannot use exec in a where clause. How about some dynamic SQL:

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'SELECT name = NULL WHERE 1 = 0';

SELECT @sql = @sql + N'
  UNION ALL SELECT name = ''' + name + ''' 
  WHERE EXISTS (SELECT 1 FROM ' + QUOTENAME(name)
  + '.sys.tables WHERE name = ''TheTableName'')'
  FROM sys.databases;

EXEC sp_executesql @sql;
like image 104
Aaron Bertrand Avatar answered Oct 09 '22 16:10

Aaron Bertrand


Powershell was built for this:

$server = new-object Microsoft.SqlServer.Management.Smo.Server ".";
foreach ($db in $server.Databases) {
   $t = $db.Tables | where {$_.Schema -eq 'YourSchema' -and $_.Name -eq 'TableName'};
   if ($t -ne $null) {
      $db.Name;
   }
}
like image 37
Ben Thul Avatar answered Oct 09 '22 15:10

Ben Thul