将EXEC结果和字符串插入表

时间:2016-08-24 16:13:29

标签: sql-server r database stored-procedures binaryfiles

我正在尝试将二进制图像存储在数据库中;该图像是在Microsoft的示例“冒险作品”数据库的R中生成的图。以下示例代码工作正常:

INSERT INTO dbo.Plots
EXEC   sp_execute_external_script
      @language = N'R'
     ,@script = N'  df <- inputDataSet; #read input data
                image_file = tempfile(); #create a temporary file
                jpeg(filename = image_file, width=500, height=500); #create a JPEG graphic device
                hist(df$Ages); #plot the histogram
                dev.off(); #dev.off returns the number and name of the new active device (after the specified device has been shut down). (device = graphical device)
                #file() opens a file, in this case the image. rb = read binary
                #readBin() reads binary data. what = described the mode of the data. In this case, it''s raw data. n = maximum number of records to read.
                #data.frame converts the data to a data frame, which is required as output by SQL Server. The result is written to the OutputDataset variable.
                OutputDataset <- data.frame(data=readBin(file(image_file,"rb"),what=raw(),n=1e6));
                    '
    ,@input_data_1 = N'SELECT Ages = DATEDIFF(YEAR,[BirthDate],GETDATE())
                        FROM [AdventureWorksDW2014].[dbo].[DimCustomer];'
    ,@input_data_1_name = N'inputDataSet'
    ,@output_data_1_name = N'OutputDataset'

但是,Plots表只有一列plot。如果我改变它以便现在每个绘图都有一个name列与之关联,我将如何更改插入查询?

我试过

INSERT INTO dbo.Plots(plot, name)
VALUES(
    (EXEC   sp_execute_external_script
          @language = N'R'
         ,@script = N'  df <- inputDataSet; #read input data
                    image_file = tempfile(); #create a temporary file
                    jpeg(filename = image_file, width=500, height=500); #create a JPEG graphic device
                    hist(df$Ages); #plot the histogram
                    dev.off(); #dev.off returns the number and name of the new active device (after the specified device has been shut down). (device = graphical device)
                    #file() opens a file, in this case the image. rb = read binary
                    #readBin() reads binary data. what = described the mode of the data. In this case, it''s raw data. n = maximum number of records to read.
                    #data.frame converts the data to a data frame, which is required as output by SQL Server. The result is written to the OutputDataset variable.
                    OutputDataset <- data.frame(data=readBin(file(image_file,"rb"),what=raw(),n=1e6));
                        '
        ,@input_data_1 = N'SELECT Ages = DATEDIFF(YEAR,[BirthDate],GETDATE())
                            FROM [AdventureWorksDW2014].[dbo].[DimCustomer];'
        ,@input_data_1_name = N'inputDataSet'
        ,@output_data_1_name = N'OutputDataset')
    , 'testname'
)

几乎围绕EXEC的括号的每个组合,列的顺序等等(我确定它需要一些括号,因为没有它们会将行, 'testname'混淆为另一个参数被传递给存储过程),但我无法避免语法错误!

0 个答案:

没有答案