Tsql 如何基于表中存在的值设置位

Tsql 如何基于表中存在的值设置位,tsql,Tsql,我有一张桌子。我有两个变量,一个是bit,另一个是int 表:WorkGroupCollectionDetail 变量:@WorkgroupID int,@IsFSBP位 该表具有WorkGroupId int PK和WorkGroupCollectionCode varchar PK。就这样 我可以运行如下查询: SELECT WorkGroupId FROM WorkGroupCollectionDetail WHERE WorkGroupCollectionCode = 'FSBP'

我有一张桌子。我有两个变量,一个是
bit
,另一个是
int

表:
WorkGroupCollectionDetail

变量:
@WorkgroupID int,@IsFSBP位

该表具有
WorkGroupId int PK
WorkGroupCollectionCode varchar PK
。就这样

我可以运行如下查询:

SELECT WorkGroupId 
FROM WorkGroupCollectionDetail 
WHERE WorkGroupCollectionCode = 'FSBP'
它给了我一个
WorkGroupID
的列表

因此,我需要做的是,如果
@WorkgroupID
的值在该查询的结果中,我需要将位变量设置为true

select @IsFBSP = case
  when exists (
    select 42 from WorkGroupDetailCollection
      where WorkGroupCollectionCode = 'FSBP' and WorkGroupId = @WorkGroupId ) then 1
  else 0 end
这在逻辑上等同于:

select @IsFBSP = case
  when @WorkGroupId in (
    select WorkGroupId from WorkGroupDetailCollection
      where WorkGroupCollectionCode = 'FSBP' ) then 1
  else 0 end
使用
存在的查询
通常比在中使用
的查询执行得更好。您可以检查执行计划,查看它们在特定情况下的比较情况


请注意,这些示例包括将位值设置为0和1。

我猜您正在寻找

Set @BitVariable = count(*)
From TestTable 
WHERE TestCode = 'TestValue' and TestID = @TestID 

您可以修改
选择
以包含对
工作组ID的检查
,并相应地更新
@IsFSBP

IF EXISTS(SELECT WorkGroupId 
          FROM WorkGroupCollectionDetail 
          WHERE WorkGroupCollectionCode = 'FSBP'
             AND WorkGroupId = @WorkgroupID)
BEGIN
   SELECT @IsFSBP = 1;
END

@BitVariable与TestTable中的行有何关联?您想用该值更新表还是在
选择中返回它?设置位变量时,您对它做了什么?位变量与表中的行无关。如果testid是查询结果的一部分,我想将BitVariable设置为true;如果不是,我想将BitVariable设置为false。我没有真正了解这一点,但这不是我需要的。抱歉。更新的答案是否更适合您更新的问题?我将尝试重新编辑我的问题。我知道我没有要求它。考虑一下你尝试过的东西,它帮助我们看到你在想什么。