2

我必须创建一个存储过程,我将在其中tableName, columnName, id作为参数传递。任务是从已传递的表中选择columnName已传递的记录id。如果找到记录,则使用一些固定数据更新记录。还要实现事务,以便我们可以在出现任何错误时回滚。

数据库中有数百个表,每个表都有不同的模式,这就是我必须通过的原因columnName

不知道什么是最好的方法。我正在尝试将记录选择到临时表中,以便我可以根据要求对其进行操作,但它不起作用。

我正在使用这段代码:

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

我收到一个错误

无效的对象名称“#TempTable”

也不确定这是否是获取数据然后更新数据的最佳方法。

4

2 回答 2

0

If you absolutely must make that work then I think you'll have to use a global temp table. You'll need to see if it exists before running your dynamic sql and clean up. With a fixed table name you'll run into problems with other connections. Inside the dynamic sql you'll add select * into ##temptable from .... Actually I'm not even sure why you want the temp table in the first place. Can't the dynamic sql just return the results?

On the surface it seems like a solid idea to have one generic procedure for returning data with a couple of parameters to drive it but, without a lot of explanation, it's just not the way database are designed to work.

于 2015-03-07T04:43:39.403 回答
0

您应该创建临时表。

IF OBJECT_ID('tempdb..##TempTable') IS NOT NULL
            DROP TABLE ##TempTable


CREATE TABLE ##TempTable()
于 2015-03-07T04:46:42.073 回答