Wednesday, October 20, 2021

sql server openrowset, z.b. zum Upload von Files in eine FileTable

openrowset dient zum öffnen von externen datenquellen, die dann wie eine tabelle in der from Klausel verwendet werden können. Es gibt 2 Syntaxe:

1.) Openrowset(BULK 'filename', SINGLE_BLOB)

Upload Files into Filetable

    ALTER PROCEDURE [dbo].[InsertFile]
    (
        @filename nvarchar(max),
        @filepath nvarchar(max)
    )   
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;

        declare @sqlStr nvarchar(max)
        set @sqlStr='INSERT INTO [dbo].StpFile ([name],[file_stream]) SELECT '''+@filename+''',* FROM OPENROWSET(BULK '''+@filepath+''', SINGLE_BLOB) AS FileData'

        Print @sqlStr
        execute (@sqlStr)
    END


2.) Openrowset('providername', 'connstr', 'query')

Stored Procedures als Views verwenden

select * from openrowset('SQLNCLI', 'Server=.\sqlexpress;Trusted_Connection=yes;','exec sp_databases') order by Database_size desc

dazu müssen adhoc verteilte Queries zugelassen sein:

sp_configure 'show advanced options', 1;  
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;  
RECONFIGURE;  
GO  


sql server bcp

einfaches beispiel für bcp:

 bcp "select name from mydb.dbo.testtable" queryout test.txt -S localhost\SqlExpress -T -c

-S Server 

-T trusted connection, oder -U username -P password

-c character Format oder -n native -N unicode native -w Unicode character Format

wenn kein Format (c,n,N,w) angegeben frägt bcp wie es jedes Feld abspeichern soll

 

Abspeichern file aus Filetable mit bcp - wichtig präfix 0 !

 die Präfix Länge muß 0 sein, sonst wird etwas zum File hinzugeschrieben !!!

C:\temp>bcp "select file_stream from mydb.dbo.MyFile where name like 'Configuration_598784a8-346a-4b7b-9817-2c7def67d1aa_Draft.zip'" queryout test.zip -S localhost\SqlExpress -T
 
Enter the file storage type of field file_stream [varbinary(max)]:
Enter prefix-length of field file_stream [8]: 0
Enter length of field file_stream [0]:
Enter field terminator [none]:
 
Do you want to save this format information in a file? [Y/n] y
Host filename [bcp.fmt]:
 
Starting copy...
 
1 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total     : 1      Average : (1000.00 rows per sec.)