sp_executesql problem

  • say this code

    @y = 'name' --- column name

    @z int ---- the output

    sq_executesql 'select count(distinct @y) from table_Name', @y , @z output

    select @z

    give error

    why any help I can't understand anythign from MSDN site

  • -- *** Test Data ***

    CREATE TABLE test

    (

    &nbsp&nbsp&nbsp&nbsp[Name] varchar(20) NOT NULL

    )

    INSERT INTO test

    SELECT 'Name1' UNION ALL

    SELECT 'Name2' UNION ALL

    SELECT 'Name1' UNION ALL

    SELECT 'Name2'

    -- *** End Test Data ***

    DECLARE @y varchar(20)

    &nbsp&nbsp&nbsp&nbsp,@z int

    &nbsp&nbsp&nbsp&nbsp,@SQLString nvarchar(4000)

    SET @y = '[Name]'

    SET @SQLString = N'SELECT @n = COUNT(DISTINCT ' + @y + N') FROM test'

    EXEC sp_executesql @SQLString, N'@n int OUTPUT', @z OUTPUT

    SELECT @z

    DROP TABLE test

  • You can't pass parameters as column names, that's the error you're no doubt getting. To do something like this, you need to build the string and execute it:

    DECLARE @y nvarchar(50) = 'name',@z int

    ,@sql nvarchar(max)

    ,@parm nvarchar(max)

    SET @sql = 'SELECT @z = COUNT(DISTINCT ' + @y + ')FROM table_Name'

    SET @parm = '@z int OUTPUT'

    EXEC sp_executesql @sql,@parm,@Z = @z OUTPUT

    SELECT @z

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

  • Oops. Right. Forgot the N in front of the strings... sorry.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply