I have a Surveys table which includes several boolean columns (where 0 = false and 1 = true). What I'm trying to do is have another table where 1 column contains the names of these columns, and the other column calculates the percentages of the true (1) occurrences. Based on this reference, I created a T-SQL Script to do this:
/****** Drop existing table ******/
DROP TABLE [dbo].[PercUsedFor]
GO
/****** Drop existing calculated values ******/
IF OBJECT_ID('GetPercUsed', 'FN') IS NOT NULL
DROP FUNCTION GetPercUsed
GO
/****** Calculate new values ******/
CREATE FUNCTION GetPercUsed (@Task nvarchar)
RETURNS DECIMAL
AS
BEGIN
DECLARE @Total INT
SELECT @Total = COUNT(*) FROM Surveys
DECLARE @Count INT
SELECT @Count = COUNT(*) FROM Surveys WHERE @Task = 1
DECLARE @Percent DECIMAL
SELECT @Percent = ((@Count / @Total) * 100)
RETURN @Percent
END
GO
/****** Create new table ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PercUsedFor](
[Task] [nvarchar](50) NULL,
[PercUsed] AS ([dbo].GetPercUsed(Task))
)
GO
/****** Fill in values ******/
INSERT INTO [dbo].[PercUsedFor] (Task)
SELECT 'Volume'
SELECT 'Speed'
SELECT 'Gap'
SELECT 'Length'
SELECT 'Stats'
GO
/****** Show table ******/
SELECT * FROM [dbo].[PercUsedFor]
GO
When I run this, the table is created, but the last line
SELECT * FROM [dbo].[PercUsedFor]"
gives me an error
Conversion failed when converting the nvarchar value 'V' to data type int.
The only place I see that could be what is causing this is in the Function at
SELECT @Count = COUNT(*) FROM Surveys WHERE @Task = 1
like it's trying to convert the value of @Task (being "Volume") into an int, instead of finding the instances of '1' in Surveys for that column.
How can I fix this? How can I make it so that I can properly use a query with a dynamic column name in the Where clause?