Hi,
    Please look at my code
    Declare @tableName varchar(100),
     @total int,
     @sql nvarchar(2000),@id varchar(4)

    set @tableName='details';
    set @id='C';
    SELECT @sql= '
    select @total = count(*) from details where id='+@id

    exec sp_executesql @sql,
    N'@total int output',
    @total output


      select @total

      Error:
      Msg 207, Level 16, State 1, Line 2
    Invalid column name 'C'.

    Please help me out.

Since @id is a character column, you have to make sure that you have the requisite quotes surrounding it when the @sql variable gets populated.

Your line 10 should look like this:

SELECT @sql= 'select @total = count(*) from details where id='''+ @id + ''''

The rest of it is fine (I tested this on a dummy table in SQL2008).

Happy coding!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.