Fixed Error: Operand data type bit is invalid for sum operator

Friday, August 3, 2012

While I am trying to add BIT filed in the SUM aggregation function and I got following error.

Error Received:

Msg 8117, Level 16, State 1, Line 1
Operand data type bit is invalid for sum operator.

For resolving this issue, we need to first cast BIT column value to INT and then pass it in SUM aggregation function. See the below example in details.

Reproduction of the error:

CREATE TABLE tbl_tmp (ID INT, Flag BIT)
GO
INSERT INTO tbl_tmp (ID, Flag)
SELECT 1, 0
UNION ALL
SELECT 2, 1
UNION ALL
SELECT 3, 0
UNION ALL
SELECT 4, 1
GO
SELECT *
FROM tbl_tmp
GO

Following script will work fine:
-- This will work fine
SELECT SUM(ID)
FROM tbl_tmp
GO

However following generate error:
-- This will generate error
SELECT SUM(Flag)
FROM tbl_tmp
GO

The workaround is to convert or cast the BIT to INT:
-- Workaround of error
SELECT SUM(CONVERT(INT, Flag))
FROM tbl_tmp
GO

1 comments:

  1. Anonymous said...

    thanks its working

Post a Comment