user3190683
user3190683

Reputation: 11

dynamic column name in sql server 2008 in stored procedure

Can I use the following syntax in stored procedure,

set @count = (select count(*) from [dbo].[employee] where @column_name ='T')

Upvotes: 1

Views: 88

Answers (1)

M.Ali
M.Ali

Reputation: 69494

CREATE PROCEDURE Proc_Name
@Column_Name NVARCHAR(128),
@COUNT INT OUTPUT
AS
BEGIN
 SET NOCOUNT ON;
  DECLARE @Sql NVARCHAR(MAX);

SET @Sql = N'SELECT @count = count(*) from [dbo].[employee] where ' + QUOTENAME(@Column_Name) 
             + N' =''T'''

EXECUTE sp_executesql @Sql
                      ,N'@COUNT INT OUTPUT'
                      ,@COUNT OUTPUT

END

Upvotes: 2

Related Questions