2016-11-23 62 views
-1

我有一個在vb.net中聲明爲變量的查詢。我想保留它的格式,以便將來的開發/更好的理解,所以在聲明級別的清理將不起作用。SQL命令字符串清理

Dim query As String = " 
SELECT * FROM (
SELECT TOP 10  T.name TableName, i.Rows NumberOfRows 
FROM  sys.tables T 
JOIN  sys.sysindexes I ON T.OBJECT_ID = I.ID 
WHERE  indid IN (0,1) 
ORDER BY i.Rows DESC, T.name ASC 
) AS TableA 
ORDER BY TableName ASC 
" 

我保留日誌從應用程序發送到數據庫的所有SQL命令的專用表,該查詢變得凌亂一旦傳遞到SQL Server作爲日誌表中的字符串值:

vbCrLf & "    SELECT * FROM (" & vbCrLf & "    SELECT TOP 10  T.name TableName, i.Rows NumberOfRows" & vbCrLf & "    FROM  sys.tables T" & vbCrLf & "    JOIN  sys.sysindexes I ON T.OBJECT_ID = I.ID" & vbCrLf & "    WHERE  indid IN (0,1)" & vbCrLf & "    ORDER BY i.Rows DESC, T.name ASC" & vbCrLf & "    ) AS TableA" & vbCrLf & "    ORDER BY TableName ASC" & vbCrLf & "    " 

所以我期待爲了擺脫所有不必要的字符。是否有任何有效和簡單的方法來清理它,以獲得乾淨的SQL語句?不需要格式化,如FROM的單獨行等。

+1

既然你已經確定了查詢工作,分配給它沒有增加的線路,比如'昏暗查詢的String =「SELECT * FROM(SELECT TOP 10 T.name表名,i.Rows NumberOfRows FROM SYS.TABLESŤJOIN SYS.SYSINDEXES I ON T.OBJECT_ID = I.ID WHERE的indid IN(0,1)ORDER BY i.Rows DESC,T.name ASC)AS表A ORDER BY表名ASC「' –

+0

那絕對是對的選擇,但我想保持它在未來的發展/更好地理解這樣的方式格式化。所以我正在尋找一種方法來擺脫所有不必要的字符。 – Megrez7

+0

由於這是一個數,大概只有管理員定定地看着它。相反,創建日誌查看器應用程序,將格式化文本,你想要的方式。無需將傳遞給服務器的內容複雜化。 –

回答

0

我終於解決了這個用正則表達式

Query = Regex.Replace(Query, "\s{2,}", " ").Trim 
0
Dim query As String ="SELECT * FROM (" & vbcrlf & 
     " SELECT TOP 10 T.name TableName, i.Rows NumberOfRows" & vbcrlf & 
     " FROM sys.tables T" & vbcrlf & 
     " JOIN sys.sysindexes I ON T.OBJECT_ID = I.ID" & vbcrlf & 
     " WHERE indid IN (0,1)" & vbcrlf & 
     " ORDER BY i.Rows DESC, T.name ASC" & vbcrlf & 
     ") AS TableA" & vbcrlf & 
     " ORDER BY TableName ASC"