如何根据表中存在的值设置位

时间:2012-10-02 21:10:07

标签: tsql

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

表:WorkGroupCollectionDetail

变量:@WorkgroupID int, @IsFSBP bit

该表格包含WorkGroupId int PKWorkGroupCollectionCode varchar PK。就是这样。

我可以运行这样的查询:

SELECT WorkGroupId 
FROM WorkGroupCollectionDetail 
WHERE WorkGroupCollectionCode = 'FSBP'

它给了我一个WorkGroupID的列表。

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

3 个答案:

答案 0 :(得分:2)

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

使用EXISTS的查询通常比使用IN的查询效果更好。您可以检查执行计划,看看它们在特定情况下的比较情况。

请注意,这些示例包括将位值设置为零以及一个。

答案 1 :(得分:1)

您可以修改SELECT以包含对WorkGroupId的检查,并相应地更新@IsFSBP

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

SQL Fiddle example

答案 2 :(得分:0)

我猜你正在寻找

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