2016-12-12 61 views
2

在處理R腳本中的破損管道時,我發現了SQL Server 2016的一個奇怪行爲。請參閱下面的T-SQL代碼:SQL Server 2016中的R腳本受到Â字符損壞

df <- data.frame(
    a = "¦", 
    b = "a,b,c" 
    ) 

不過,最終的結果選項卡看起來是這樣的:

BadEncodingColumn GoodEncodingColumn 
¦     a,b,c 

DECLARE 
    @r nvarchar(100) 

/* Create a data frame with a broken pipe as one of its fields and a simple ASCII encoded string in another. */ 
SET @r = N' 
df <- data.frame(
    a = "¦", 
    b = "a,b,c" 
    )'; 

/* Print @r to detect the inclusion of any unwanted characters. */ 
PRINT @r; 

/* Execute and retrieve the output. */ 
EXECUTE sp_execute_external_script 
    @language = N'R', 
    @script = @r, 
    @output_data_1_name = N'df' 
WITH RESULT SETS ((
    BadEncodingColumn varchar(2), 
    GoodEncodingColumn varchar(5) 
    )); 

在消息選項卡中的打印命令返回此行爲似乎出現在腳本的EXECUTE sp_execute_external_script階段,並且在處理Excel,R和其他版本的SQL Server的其他編碼問題時,我看到了此字符(Â)。

此行爲的任何解決方案?還有獎勵點,對角色有什麼特別的?

編輯:我試圖修補SQL Server和R內的數據類型無濟於事。

+0

真的不知道爲什麼這是downvoted,好像對我有效的,新穎的問題進行更新。 –

回答

3

這個問題似乎與在R腳本中編碼非ASCII字符(斷開的管道在128個ASCII字符之外)有關。您可以使用'Encoding'函數將編碼重寫爲Unicode(UTF-8)來解決該問題。比如你的腳本可以按如下

DECLARE 
    @r nvarchar(100) 

/* Create a data frame with a broken pipe as one of its fields and a simple ASCII encoded string in another. */ 
SET @r = N' 
df <- data.frame(
    a = "¦", 
    b = "a,b,c" 
    ) 

Encoding(levels(df$a)) <- "UTF-8" ###### Encoding override' 

/* Print @r to detect the inclusion of any unwanted characters. */ 
PRINT @r; 

/* Execute and retrieve the output. */ 
EXECUTE sp_execute_external_script 
    @language = N'R', 
    @script = @r, 
    @output_data_1_name = N'df' 
WITH RESULT SETS ((
    BadEncodingColumn varchar(2), 
    GoodEncodingColumn varchar(5) 
    )); 

產生以下結果

BadEncodingColumn GoodEncodingColumn 
¦     a,b,c 
+0

謝謝! –