Inline SQL To Set Fully Qualified Name Why does my variable @FQN not set accordingly?  Is this a problem with my syntax?  A Problem with using a cursor?  What should I do so that my variable @FQN sets appropriately?  This is what my print statements show, my variable @table outputs properly, but my variable @FQN never changes?


  OneTwoThree
  Select Top 1 * FROM servername.database.dbo.newdatabase 
  FourFiveSix
  Select Top 1 * FROM servername.database.dbo.newdatabase 
  FourOmegaSix
  Select Top 1 * FROM servername.database.dbo.newdatabase 


And here is full syntax:

Declare @table varchar(100), @sql varchar(4000), @FQN varchar(MAX)
Create Table #tablename (tablename varchar(1000))
Insert Into #tablename Values
('OneTwoThree'),
('FourFiveSix'),
('FourOmegaSix')

Declare c1 Cursor For

Select tablename
FROM #tablename

Open c1 

Fetch Next From c1 Into @table

While @@FETCH_STATUS = 0
Begin
  if @table = 'OneTwoThree'
    BEGIN
        SET @FQN = 'servername.database.dbo.onetwothree'
    END
  if @table = 'FourFiveSix'
    BEGIN
        SET @FQN = 'servername.database.dbo.fourfivesix'
    END
  if @table != 'OneTwoThree' or @table != 'fourfivesix'
    BEGIN
        SET @FQN = 'servername.database.dbo.newdatabase'
    END
  Print @table

  Set @sql = 'Select Top 1 * '
             +'FROM '+@FQN+' '

  Print @sql

  Fetch Next From c1 Into @table

End

Close c1
Deallocate c1

Drop Table #tablename
Simplify:

SET @FQN = 'servername.database.dbo.newdatabase';

IF @table = 'OneTwoThree'
BEGIN
    SET @FQN = 'servername.database.dbo.onetwothree';
END

IF @table = 'FourFiveSix'
BEGIN
    SET @FQN = 'servername.database.dbo.fourfivesix';
END


Or:

SET @FQN = 'servername.database.dbo.' + CASE @table
  WHEN 'OneTwoThree' THEN 'onetwothree'
  WHEN 'FourFiveSix' THEN 'fourfixesix'
  ELSE 'newdatabase'
END;


Or even:

SET @FQN = 'servername.database.dbo.' + CASE 
  WHEN @table IN ('OneTwoThree', 'FourFiveSix')
  THEN LOWER(@table) ELSE 'newdatabase'
END;


Also, you can do this whole thing without the cursor:

DECLARE @sql nvarchar(4000) = N'', -- always use nvarchar for dynamic SQL
        @FQN nvarchar(4000) = N'servername.database.dbo.';

CREATE TABLE #tablename (tablename varchar(1000));

INSERT #tablename(tablename) VALUES('OneTwoThree'),('FourFiveSix'),('FourOmegaSix');

SELECT @sql += N'
  SELECT TOP 1 * FROM ' + @FQN + CASE
  WHEN tablename IN ('OneTwoThree', 'FourFiveSix')
  THEN LOWER(tablename) ELSE N'newdatabase' END + N'; --' + tablename
FROM #tablename;

PRINT @sql;

DROP TABLE #tablename;


Output:

  SELECT TOP 1 * FROM servername.database.dbo.onetwothree; --OneTwoThree
  SELECT TOP 1 * FROM servername.database.dbo.fourfivesix; --FourFiveSix
  SELECT TOP 1 * FROM servername.database.dbo.newdatabase; --FourOmegaSix


(There's still a hidden loop there, but it's far less code to look at, maintain, etc.)