开发者

Dynamic SQL - something up with the where clause

开发者 https://www.devze.com 2023-01-30 17:18 出处:网络
I have this proc: Create PROCEDURE [dbo].[myProc] @TableName nvarchar(100), @RowID int AS BEGIN SET @SQLQuery = \'Select * from \' + @TableName + \' where ID = \' + @RowID ;

I have this proc:

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100), 
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ' + @RowID ; 
    EXECUTE(@SQLQu开发者_JAVA百科ery); 
END

I basically want to return the resulting row from this, without a where clause, its all good.


You need to be very careful as you've opened yourself up to SQL injection attacks. I'd strongly recommend being very defensive with this and parameterise as much as possible. e.g.

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100), 
@RowID int
AS
BEGIN
    DECLARE @SQLQuery NVARCHAR(500); 
    IF (OBJECT_ID(@TableName) IS NOT NULL)
        BEGIN
            SET @SQLQuery = 'Select * from ' + QUOTENAME(@TableName) + ' where ID = @RowId' 
            EXECUTE sp_executesql @SQLQuery, N'@RowId INTEGER', @RowID
        END
END

It would also be worth considering "locking down" what @TableName values are explicitly supported - check against a whitelist before building/executing the dynamic SQL.


in case that ID is varchar try this:

Create PROCEDURE [dbo].[myProc]
@TableName nvarchar(100), 
@RowID int

AS
BEGIN
    SET @SQLQuery = 'Select * from ' + @TableName + ' where ID = ''' + rtrim(ltrim(str(@RowID))) + ''''; 
    EXECUTE(@SQLQuery); 
END
0

精彩评论

暂无评论...
验证码 换一张
取 消