0
/****** Script for SelectTopNRows command from SSMS  ******/
DECLARE @user int;
DECLARE @aipNip varchar(20);
DECLARE @accessToBaseCompanies TABLE (baseCompanyId INT);

SET @user = 1;

INSERT INTO @accessToBaseCompanies (baseCompanyId) 
((SELECT c.BaseCompanyFk FROM [dbo].Companies c WHERE c.CompaniesTeamFk IN (SELECT u.CompaniesTeamFk FROM [dbo].[CompaniesTeams_Users] u WHERE UserFk = @user))
UNION ALL
(SELECT c.BaseCompanyFk FROM [dbo].Beneficiaries c WHERE c.DepartmentFk IN (SELECT u.DepartmentFk FROM [dbo].[Departments_Users] u WHERE UserFk = @user)))

SET @aipNip = (SELECT TOP 1 fc.[PureNip]
FROM [dbo].[BaseCompanies] bc
INNER JOIN [dbo].[Companies] c ON bc.Id = c.BaseCompanyFk AND c.CompanyType = 1
INNER JOIN [dbo].[Payment_Partners] fc ON fc.id = bc.CompanyPartnerFk)

SELECT bc.[Id]
      ,bc.[Name] as 'BaseCompany'
      ,SUM(cd.[PaidAmountNavireo]) - SUM(cd.[GrossTotal])
      ,SUM(CASE WHEN (ps.Id = 1 OR ps.Id = 3)
  FROM [dbo].[BaseCompanies] bc
  INNER JOIN [dbo].[Payment_CostDocuments] cd ON bc.Id = cd.BaseCompanyFk
  INNER JOIN [dbo].[PaymentStatuses] ps ON ps.Id = cd.PaymentStatusFk
  INNER JOIN [dbo].[Payment_Partners] fc ON fc.Id = cd.PartnerFk

  WHERE bc.[Id] IN @accessToBaseCompanies

Team BY
bc.[Id],
bc.[Name]

@accessToBaseCompanies 不为空,为什么当我尝试执行查询时出现错误:'@accessToBaseCompanies' 附近的语法不正确。

4

3 回答 3

12

to 的参数IN是值列表或子查询,而不是表。尝试:

WHERE bc.[Id] IN (select baseCompanyId from @accessToBaseCompanies)
于 2013-07-15T11:17:27.713 回答
4

问题是这一行:

WHERE bc.[Id] IN @accessToBaseCompanies

它应该是:

WHERE bc.[Id] IN (select baseCompanyId from @accessToBaseCompanies)
于 2013-07-15T11:18:15.563 回答
1

建议使用 EXISTS 而不是 IN,通常首先更高效(SQL Server IN 与 EXISTS 性能)。更换

WHERE bc.[Id] IN @accessToBaseCompanies

经过

WHERE EXISTS (SELECT 1 FROM @accessToBaseCompanies a where a.baseCompanyId = bc.[Id] )
于 2013-07-15T11:29:46.993 回答