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
精彩评论