I was looking how I can parameterize table names and so I found dynamic sql queries. I finally got the proc saved, but when I execute it errors out with “Conversion failed when converting the varchar value ‘ AND ID =’ to data type int.” I have no idea what is going wrong when I try to execute this stored proc. I feel like it must be a typo but I cannot tell. The stored pro.
EDITED to incorporate the suggestion below. Still no luck unless I am doing this wrong.
-- ======================================================= -- Create Stored Procedure Template for Azure SQL Database -- ======================================================= SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author, , Name> -- Create Date: <Create Date, , > -- Description: <Description, , > -- ============================================= ALTER PROCEDURE [dbo].[sp_GetFormFieldCDC] ( @formfieldId INT, @C___operation INT, @C___start_lsn binary(10), @tablename NVarchar(255) ) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON DECLARE @ActualTableName AS NVarchar(255) SELECT @ActualTableName = QUOTENAME( TABLE_NAME ) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tablename DECLARE @sql AS NVARCHAR(MAX) SELECT @sql = 'SELECT * FROM ' + @ActualTableName + ' WHERE __$start_lsn =' + CONVERT(NVARCHAR(255),@C___start_lsn) + ' AND __$operation =' + @C___operation + ' AND ID =' + @formfieldId + ';' -- Insert statements for procedure here EXEC sp_executesql @SQL, N' @formfieldId INT, @C___operation INT, @C___start_lsn binary(10), @tablename NVarchar(255)', @formfieldId , @C___operation, @C___start_lsn, @tablename END GO
Advertisement
Answer
You should pass the parameters all the way through to sp_executesql
. Do not inject them, unless they are object names, in which case you need QUOTENAME
.
You can also use
OBJECT_ID
to check for table existence, and throw an exception if there is no such object.
CREATE OR ALTER PROCEDURE [dbo].[GetFormFieldCDC] ( @formfieldId INT, @C___operation INT, @C___start_lsn binary(10), @schemaname sysname, @tablename sysname ) AS SET NOCOUNT ON; IF (OBJECT_ID(QUOTENAME(@schemaname) + '.' + QUOTENAME(@tablename)) IS NULL) THROW 50000, 'Table not found', 0; DECLARE @sql AS NVARCHAR(MAX) = ' SELECT * FROM ' + QUOTENAME(@schemaname) + '.' + QUOTENAME(@tablename) + ' WHERE __$start_lsn = @C___start_lsn AND __$operation = @C___operation AND ID = @formfieldId; '; EXEC sp_executesql @SQL, N' @formfieldId INT, @C___operation INT, @C___start_lsn binary(10)', @formfieldId = @formfieldId, @C___operation = @C___operation, @C___start_lsn = @C___start_lsn; GO