The Way to Programming
The Way to Programming
How to pass table name and guid to a stored procedure
I’d get rid of all unnecessary variables. Also, to look up a guid, the literal must be in the correct format, with dashes.
CREATE PROCEDURE [dbo].[sp_GetUserID] @tableName varchar (250), @formSecret varchar (100) AS SET NOCOUNT ON; IF @formSecret NOT LIKE '%-%-%-%-%' SET @formSecret = STUFF(STUFF(STUFF(STUFF(@formSecret, 21, 0, '-'), 17, 0, '-'), 13, 0, '-'), 9, 0, '-') EXEC('SELECT id,emailSent from [' + @tablename + '] WHERE formSecret = ''' + @formSecret + '''') GO
I had tried all the options with apostrophes and every time I ran it, it complained it couldn’t find the column ‘(whatever the formsecret value was at the time)’. Then I read something over at SQL Authority and wound up converting the statement to:
set @sql = 'select id, emailSent from ' + @tablename + ' WHERE formSecret = ' + CHAR(39) + @formSecret + CHAR(39)
– which worked.
I also implemented the Exec sp_executesql as suggested by ste5an – and learned in the implementing that the @sql needed to be an nvarchar to work properly – so multiple things learned.
As to the SQL injection, this is getting called from a web form that may get 100 uses on a really busy day. The form uses the php pdo module with stored procedures and parameterized queries all around. Each variable is bound to a specific datatype as well. I understand that is a very secure approach, but if that understanding is wrong, I have no problem switching it up as needed.
Sign in to your account