English 中文(简体)
常规选择存储过程
原标题:Generic Select Stored Procedure

我想创建一个基于以下方式的存储过程:

ALTER PROCEDURE spGetLastId
(
@table_name varchar(100)
)
AS
BEGIN
    DECLARE @DBSql varchar(2000)
    SET @DBSql =  SELECT MAX(id) as   LastId   FROM   + @table_name
    EXEC sp_executesql @DBSql
END 

这个过程必须显示我作为参数传递的任何表的最后一个id。

感谢和问候,

最佳回答

@DBSqlvarchar更改为nvarchar即可,或者查看内置的IDENT_CURRENT()

问题回答

不确定这是否是您想要的,但如果您重新插入记录,然后检索生成的最后一个标识值,则可以在插入后使用SELECT SCOPE_identity()。。。

INSERT INTO MyTable (col1, col2) 
VALUES (val1, val2);
SELECT SCOPE_IDENTITY()

否则,您的过程应该符合您的要求,尽管您应该将@DbSql的数据类型更改为nvarchar而不是varchar。

我所知道的做这类工作的唯一用例是使用构建自己的IDENTITY字段。

如果您正在执行此操作,请停止并使用SQL Server提供的IDENTITY。

如果您想将自己的值插入IDENTITY列,请参阅上设置IDENTITY_INSERT TABLENAME;





相关问题
SQL Server database is not visible

I have installed ASP.NET application with database on our server. ASP.NET application created database using connection string below. The problem is that I do not see database in SQL Server Management ...

Most efficient way to store number 11.111 in SQL Server

What datatype is the most efficient to store a number such as 11.111. The numbers will have up 2 digits before the point and up to three after. Currently the column is a bigint , I am guessing that ...

表格和数据表

是否需要在提瓜表之后更新表格统计数据,还是自动更新?

Inconsistent Generate Change Script

I add a column of type tinyint and being set to not allow nulls in a table and generate the change scripts. The table has data in it at this time. The script has code that creates a temp table and ...

Performance of Sql subqueriesfunctions

I am currently working on a particularly complex use-case. Simplifying below :) First, a client record has a many-to-one relationship with a collection of services, that is, a single client may have ...

selecting one value out of an xml column

I have a particularly troublesome xml column to query data from. The schema is fixed by the Quebec Ministry of Revenue so "it is what it is" The important part of the query looks like this: with ...

Selecting records during recursive stored procedure

I ve got a content management system that contains a hierarchical structure of categories, with sub-categories subject to different ordering options at each level. Currently, that s retrieved by a (...

热门标签