Search code examples
sqlsql-serverdenormalization

Select by a key for all associated records from a denormalizing database


I am using SQL server 2012. I just have access to a database that does not have any relationships yet. I don't know much about SQL script. I want to see all the records that associate to EmployeeID 102 from all tables that have column EmployeeID. E.g.

EmployeeID    LastName     FirstName   (from table Employees)
102           Jonh         Smith
EmployeeID    HireDate                 (from table EmploymentRecords)
102           2/1/2014
EmployeeID    Monthly Salary           (from table Salary)
102           2000
and so on

I tried the following script, but the Result window become closed and on Message window it just said "Command(s) completed successfully". How can I get the above results. Thanks in advance.

DECLARE tnames_cursor CURSOR
FOR
  SELECT TABLE_NAME 
  FROM INFORMATION_SCHEMA.TABLES
OPEN tnames_cursor
DECLARE @tablename sysname
FETCH NEXT FROM tnames_cursor INTO @tablename

if (select count(*) from information_schema.columns where  table_name = @tablename and     Column_name ='EmployeeID') > 0

BEGIN   

  SELECT @tablename = RTRIM(@tablename) 
  EXEC ('SELECT *  FROM '+ @tablename +'where  EmployeeID = 102')
END

Solution

  • This statement will probably prevent everything from working:

    EXEC ('SELECT *  FROM '+ @tablename +'where  EmployeeID = 102')
    

    You need a space after the table name:

    EXEC ('SELECT *  FROM '+ @tablename +' where  EmployeeID = 102')
    

    In addition, your cursor logic seems off. You should be checking for @@FETCH_STATUS and then closing and deallocating the cursor.

    Follow the example at the end of the documentation.