title: SQL Server : dynamically change database name in SELECT statement based on a variable
body: <p>I have a query that looks mostly like:</p>
  
  <pre><code> DECLARE @Vendor varchar (50)
  --SET @Vendor = 55 --One vendor
  --Set @Vendor = 234 --Another vendor
  --SET @Vendor = 123 --Another vendor
  
  SELECT column1, column2, column3
  FROM [dbo].[TABLE1]
  WHERE vendor_key = @Vendor
    AND create_date &gt; CONVERT(VARCHAR, GETDATE(), 112)
  ORDER BY column1;
  
  SELECT column1, column2, column3
  FROM [dbo].[TABLE2]
  WHERE vendor_key = @Vendor
    AND create_date &gt; CONVERT(VARCHAR, GETDATE(), 112)
  ORDER BY column1;
  </code></pre>
  
  <p>I cycle through the list of vendor numbers that are commented out by uncommenting whichever vendor I need info on.  (It's a much longer list than just the 3 listed above.  This lets me use one query for all vendors, and without having to memorize the vendor numbers). </p>
  
  <p>The only annoyance is that there are a bunch of different databases on the same server, and depending on the vendor, I need to manually select the correct db from the drop down.</p>
  
  <p>Ideally, I would like to write some kind of IF statement that will either SET the database name, or replace the "[dbo]" in front of the table name, depending on what the vendor number is that gets set above.</p>
  
  <p>So like, </p>
  
  <pre><code>IF @Vendor = 55 
     SET @database = "Vendor1DB", 
  ELSE IF @Vendor = 234 
     SET @database = "Vendor2DB" (and so on)
  </code></pre>
  
  <p>Is this possible?</p>