Home Forums SQL Server 2008 T-SQL (SS2K8) Trying to pass a value to a variable from dynamic sql RE: Trying to pass a value to a variable from dynamic sql

  • Quick questions:

    1. Why are you using Dynamic SQL when a normal query would be enough?

    2. Why aren't you parametrizing your Dynamic SQL leaving it open to SQL Injection?

    3. Why are you using IN for a single value?

    Static SQL example:

    SELECT @MinBoundary = Convert(DateTime, MIN(PRV.value))

    FROM sys.partition_functions AS PF

    JOIN sys.partition_parameters AS PP

    ON PF.function_id = PP.function_id

    JOIN sys.types AS T1

    ON T1.system_type_id = PP.system_type_id

    JOIN sys.types AS T2

    ON T2.user_type_id= PP.user_type_id

    JOIN sys.partition_range_values AS PRV

    ON PP.function_id = PRV.function_id

    AND PP.parameter_id = PRV.parameter_id

    WHERE PF.name = 'WBC_' + @TableName + '_pf'

    PRINT @MinBoundary

    Dynamic SQL example parametrized query:

    DECLARE @MinBoundary DateTime, @s-2 nvarchar(max)

    declare @DBName sysname, @TableName sysname

    select @DBName = 'MyDB', @TableName = 'MyTable'

    select @s-2 = '

    SELECT @MB=Convert(DateTime, MIN(PRV.value))

    FROM sys.partition_functions AS PF

    JOIN sys.partition_parameters AS PP

    ON PF.function_id = PP.function_id

    JOIN sys.types AS T1

    ON T1.system_type_id = PP.system_type_id

    JOIN sys.types AS T2

    ON T2.user_type_id= PP.user_type_id

    JOIN sys.partition_range_values AS PRV

    ON PP.function_id = PRV.function_id

    AND PP.parameter_id = PRV.parameter_id

    WHERE PF.name IN (''WBC_'' + @TN + ''_pf'')'

    print @s-2

    EXECUTE sp_executesql @s-2, N'@MB DateTime OUTPUT, @TN sysname', @MB=@MinBoundary OUTPUT, @TN=@TableName

    PRINT @MinBoundary

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2