[英]SQL: last id from a table selecting database
I have the following query in my php script: 我的php脚本中有以下查询:
SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MYTABLE' AND last_value IS NOT NULL
This works great, it returns the last id from MYTABLE which is what I need. 这很好用,它返回我需要的MYTABLE的最后一个ID。
But, as I'm going to have more than one database I should modify the query to select the database where MYTABLE is. 但是,由于我将拥有多个数据库,因此我应该修改查询以选择MYTABLE所在的数据库。
I'm doing: 我正在做:
SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'mydatabase.dbo.MYTABLE' AND last_value IS NOT NULL
But this does not work, I get nothing in return. 但这是行不通的,我一无所获。
Any ideas? 有任何想法吗?
Thanks a lot! 非常感谢!
When you execute an SQL statement, it runs in the context of a database you specified on connection. 执行SQL语句时,它在您在连接上指定的数据库的上下文中运行。 In order to query a different database you should change the database context.
为了查询其他数据库,您应该更改数据库上下文。 Try this:
尝试这个:
USE MyDatabase;
SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MYTABLE' AND last_value IS NOT NULL
If you need to pass the database name as a variable IDENT_CURRENT accepts a database qualified object name. 如果需要将数据库名称作为变量传递,则IDENT_CURRENT接受数据库限定的对象名称。 eg:
例如:
SELECT IDENT_CURRENT('mydatabase.dbo.MYTABLE');
As an unrelated aside it would be better to use: 除了不相关的以外,最好使用:
WHERE OBJECT_ID = OBJECT_ID(N'MYTABLE');
Instead of 代替
WHERE OBJECT_NAME(OBJECT_ID) = 'MYTABLE'
Since if MYTABLE
was not in the default schema, it would fail, consider a table MYSCHEMA.MYTABLE. 由于如果
MYTABLE
不在默认模式中,则它将失败,因此请考虑使用表MYSCHEMA.MYTABLE。 This returns no rows 这将不返回任何行
WHERE OBJECT_NAME(OBJECT_ID) = 'MYSCHEMA.MYTABLE'
Whereas this would: 而这将:
WHERE OBJECT_ID = OBJECT_ID(N'MYSCHEMA.MYTABLE');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.