WHERE语句中的TSQL表变量会导致错误

时间:2013-07-15 11:16:20

标签: sql sql-server tsql

/****** 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'附近的语法不正确。

3 个答案:

答案 0 :(得分:10)

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

WHERE bc.[Id] IN (select baseCompanyId from @accessToBaseCompanies)

答案 1 :(得分:4)

问题在于这一行:

WHERE bc.[Id] IN @accessToBaseCompanies

应该是:

WHERE bc.[Id] IN (select baseCompanyId from @accessToBaseCompanies)

答案 2 :(得分:1)

建议使用EXISTS代替IN,通常首先使用效率更高(SQL Server IN vs. EXISTS Performance)。替换

WHERE bc.[Id] IN @accessToBaseCompanies

通过

WHERE EXISTS (SELECT 1 FROM @accessToBaseCompanies a where a.baseCompanyId = bc.[Id] )