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