I have to create a stored procedure where I will pass tableName, columnName, id
as parameters. The task is to select records from the passed table where columnName
has passed id
. If record is found update records with some fixed data. Also implement Transaction so that we can rollback in case of any error.
There are hundreds of table in database and each table has different schema that is why I have to pass columnName
.
Don't know what is the best approach for this. I am trying select records into a temp table so that I can manipulate it as per requirement but its not working.
I am using this code:
ALTER PROCEDURE [dbo].[GetRecordsFromTable]
@tblName nvarchar(128),
@keyCol varchar(100),
@key int = 0
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
--DROP TABLE #TempTable;
DECLARE @sqlQuery nvarchar(4000);
SET @sqlQuery = 'SELECT * FROM ' + @tblName + ' WHERE ' + @keyCol + ' = 2';
PRINT @sqlQuery;
INSERT INTO #TempTable
EXEC sp_executesql @sqlQuery,
N'@keyCol varchar(100), @key int', @keyCol, @key;
SELECT * FROM #TempTable;
END TRY
BEGIN CATCH
EXECUTE [dbo].[uspPrintError];
END CATCH;
END
I get an error
Invalid object name '#TempTable'
Also not sure if this is the best approach to get data and then update it.