这是我创建的一个存储过程,用于使用 OLE 自动化和 ADO 的 Stream 对象读取离线 .mdf。此解决方案和更多上下文也发布在此处:https ://social.technet.microsoft.com/Forums/sqlserver/en-US/3de5b574-0751-44a2-b69f-fa0c20378359/how-to-determine-sql-server -version-of-an-mdf-file?forum=sqlsetupandupgrade
CREATE /*ALTER*/ PROCEDURE spDBVersion
(
@FilePath nvarchar(500) /*Your filepath here EG 'C:\SQLData\somedatabase.mdf'*/
)
AS
DECLARE @HR int,
@objStream int,
@strErrorMessage Varchar(1000),
@Source nvarchar(255),
@Desc nvarchar(255),
@offset bigint,
@binary1 binary,
@binary2 binary
SET NOCOUNT ON
SELECT @strErrorMessage='Creating ADO stream object'
EXEC @HR = sp_OACreate 'ADODB.Stream' , @objStream OUT
IF @HR <> 0 GOTO CLEANUP
SELECT @strErrorMessage='Opening ADO stream'
EXEC @HR = sp_OAMethod @objStream, 'Open'
IF @HR <> 0 GOTO CLEANUP
SELECT @strErrorMessage='Declaring ADO stream type binary'
EXEC @HR = sp_OASetProperty @objStream, 'Type', 1
IF @HR <> 0 GOTO CLEANUP
SELECT @strErrorMessage='Opening File into ADO stream'
EXEC @HR = sp_OAMethod @objStream, 'LoadFromFile', NULL , @FilePath
IF @HR <> 0 GOTO CLEANUP
SELECT @offset = 73828 --9 * 8192 + 96 + 4
SELECT @strErrorMessage='Setting offset to read file'
EXEC @HR = sp_OASetProperty @objStream, 'Position', @offset
IF @HR <> 0 GOTO CLEANUP
SELECT @strErrorMessage = 'Reading Version number from mdf'
EXEC @HR = sp_OAMethod @objstream, 'Read', @binary1 OUT , 1
IF @HR <> 0 GOTO CLEANUP
SELECT @strErrorMessage = 'Reading Version number from mdf'
EXEC @HR = sp_OAMethod @objstream, 'Read', @binary2 OUT , 1
IF @HR <> 0 GOTO CLEANUP
SELECT @binary1 + 256 * @binary2 AS DatabaseVersion
END_ROUTINE:
RETURN
CLEANUP:
BEGIN
EXEC sp_OAGetErrorInfo @objStream,
@Source OUT,
@Desc OUT;
SELECT ErrorInSP='spDBVersion',
HR = convert(varbinary(4),@HR),
Source=@Source,
Description=@Desc,
Process=@strErrorMessage
GOTO END_ROUTINE
END
GO
此存储过程需要 OLE 自动化,因此您需要将其包装在一些重新配置语句中,假设 OLE 已禁用(可能应该如此)。
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
GO
exec spDBVersion 'E:\SQLData\somedatabase.mdf'
GO
EXEC sp_configure 'Ole Automation Procedures', 0
RECONFIGURE
GO
EXEC sp_configure 'show advanced options', 0
RECONFIGURE
GO