• GSquared (12/12/2012)


    jeetsingh.cs (12/12/2012)


    See Dyanmic Sql is used where we dont want to hard code the values in

    our query.

    For example if we wan to run this command against a database

    than

    Create procedure dynamic_query(

    @dbname As nvarchar(25)

    )

    as

    BEGIN

    declare @sql_txt nvarchar(MAX)

    SET @sql_txt=' Use '+@dbname +' select * from sys.objects'

    EXEC(@SQL)

    END

    I would recommend modifying that so that it first checks to see if @dbname is a valid database name (check vs sys.databases), then use QuoteName() to make sure it's going to deal with non-alpha characters correctly.

    These two steps will avoid a number of potential errors, and also make it injection-safe.

    Also, Exec() won't accept an NVarchar(max) input string.

    I might have missed something, but I believe SQL Server 2005 was the first to allow NVARCHAR(MAX) in EXEC calls and in SP_ExecuteSQL as well.