使用File I / O Api创建映像后获取FileTable stream_id

时间:2019-06-08 07:38:37

标签: sql sql-server tsql filetable

我尝试使用文件I / O API将图像文件插入SQL Server FileTable目录。我需要获取stream_id插入的图像,并将其用作另一个表作为外键。

任何人都可以帮助我,如何获得创建的图片stream_id

1 个答案:

答案 0 :(得分:3)

创建文件后,您需要使用带有新创建的文件路径的T-SQL查询文件表以获取stream_id。最好使用唯一文件表path_locator列来完成此操作。

下面是示例存储过程和用法示例,这些示例使用相对或完整UNC路径获取文件的唯一stream_id。文件表的path_locator具有唯一的约束索引,因此这些查询非常有效。

CREATE DATABASE FileTableExample
    ON  PRIMARY 
    ( NAME = N'FileTableExample', FILENAME = N'D:\SqlFiles\FileTableExample.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10MB ), 
     FILEGROUP FileStreamFG CONTAINS FILESTREAM  DEFAULT
    ( NAME = N'FileTableExample_FileStream', FILENAME = N'D:\SqlFiles\FileTableExample_FileStreamFG' , MAXSIZE = UNLIMITED) 
     LOG ON 
    ( NAME = N'FileTableExample_log', FILENAME = N'D:\SqlFiles\FileTableExample_log.ldf' , SIZE = 10MB , MAXSIZE = UNLIMITED, FILEGROWTH = 10MB );
GO

ALTER DATABASE FileTableExample SET FILESTREAM( NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'FileTableExample' ) 
GO

USE FileTableExample;
GO

CREATE TABLE [dbo].[Images] AS FILETABLE ON [PRIMARY] FILESTREAM_ON [FileStreamFG];
WITH
(
    FILETABLE_DIRECTORY = N'Images', FILETABLE_COLLATE_FILENAME = SQL_Latin1_General_CP1_CI_AS
);
GO

CREATE PROC dbo.GetStreamIDByRelativePath
    @RelativeFilePath nvarchar(MAX)
AS
SELECT stream_id
FROM dbo.Images
WHERE path_locator = GetPathLocator(FileTableRootPath() + @RelativeFilePath);
GO

EXEC dbo.GetStreamIDByRelativePath @RelativeFilePath = N'\Images\YourImageFile.png';
GO

CREATE PROC dbo.GetStreamIDByFullUNCPath
    @FullUNCPath nvarchar(MAX)
AS
SELECT stream_id
FROM dbo.Images
WHERE path_locator = GetPathLocator(@FullUNCPath);
GO

EXEC dbo.GetStreamIDByFullUNCPath @FullUNCPath = N'\\YourSqlServer\YourFileStreamShare\YourDatabaseFileSteamDirectory\Images\YourImageFile.png';
GO