当前位置: 代码迷 >> Sql Server >> 如何通过不同的值查找不同的表
  详细解决方案

如何通过不同的值查找不同的表

热度:8   发布时间:2016-04-27 11:33:06.0
怎么通过不同的值查找不同的表
我现在有3个表:User表 Expert表 Enterprise表

怎么通过User表中的UserType来确定是查找Expert表还是查找Enterprise表

并且能生成一个视图

------解决方案--------------------
SQL code
--> 测试数据:@Userdeclare @User table([ID] int,[Name] varchar(1),[UserType] int)insert @Userselect 1,'a',1 union allselect 2,'b',1 union allselect 3,'c',2 union allselect 4,'d',2--> 测试数据:@Expertdeclare @Expert table([ID] int,[c1] varchar(1))insert @Expertselect 1,'a' union allselect 2,'b' union allselect 3,'c' union allselect 4,'d'--> 测试数据:@Enterprisedeclare @Enterprise table([ID] int,[c1] varchar(1))insert @Enterpriseselect 5,'a' union allselect 6,'b' union allselect 7,'c' union allselect 8,'d'select * from @User aLEFT JOIN @Expert b ON a.[UserType]=1 AND a.name=b.[c1]LEFT JOIN @Enterprise c ON a.[UserType]=2 AND a.name=c.[c1] /*ID          Name UserType    ID          c1   ID          c1----------- ---- ----------- ----------- ---- ----------- ----1           a    1           1           a    NULL        NULL2           b    1           2           b    NULL        NULL3           c    2           NULL        NULL 7           c4           d    2           NULL        NULL 8           d*/
  相关解决方案