• 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.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon