听起来您想要类似于Group_Concat
SQL Server中的 mySQL 的东西?
如果您正在寻找一种方法来执行此操作,以便每个 companyid 位于单独的列中,那么使用动态 SQL 可能会遇到一些困难。在什么时候将它返回给应用程序并让它在自己的逻辑中处理它需要的东西可能会更容易?
顺便说一句,动态 SQL 逻辑会像这样,以防您想知道...注意它有多讨厌...这就是为什么我建议反对它。
select @highestCount = max(count(*))
from employeeCompany
group by Employeeid
declare createtemptable varchar(max), @filltableselect varchar(max), @filltablejoin varchar(max)
declare @currentCount int
set @currentCount = 0
set @createtemptable = 'CREATE TABLE #Temp (EmployeeID INT'
set @filltableselect = 'INSERT INTO #Temp SELECT EmployeeCompany0.EmployeeID, EmployeeCompany0.CompanyID'
set @filltablejoin = 'FROM EmployeeCompany AS EmployeeCompany0'
while(@currentCount < @highestCount)
begin
set @createtemptable = @createtemptable + ', CompanyID'
+ CAST(@currentCount AS VARCHAR(2)) + ' INT'
if(@currentCount > 0)
begin
set @filltableselect = @filltableselect + ', EmployeeCompany'
+ CAST(@currentCount AS VARCHAR(2)) + '.CompanyId'
set @filltablejoin = @filltablejoin
+ 'LEFT JOIN EmployeeCompany AS EmployeeCompany'
+ CAST(@currentCount AS VARCHAR(2))
+ ' ON EmployeeCompany0.EmployeeID = EmployeeCompany'
+ CAST(@currentCount AS VARCHAR(2)) + '.EmployeeID'
end
set @currentCount = @currentCount + 1
end
set @createtemptable = @createtemptable + ')'
--This next line can be whatever you need it to be
set @filltablejoin = @filltablejoin + 'WHERE employeeCompany0.EmployeeID = 1'
exec @createtemptable
exec @filltableselect + @filltablejoin