2012-11-21 59 views
1

我有這個查詢。所有選擇在技術上都是相同的,只是乘數的遞增值。我需要這個* 64。SQL遞增查詢

有關如何以比我現在做的更有效的方式做到這一點的任何建議?

SELECT 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*1, 2)) as BINARY(2))) AS inventory1, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*2, 2)) as BINARY(2))) AS inventory2, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*3, 2)) as BINARY(2))) AS inventory3, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*4, 2)) as BINARY(2))) AS inventory4, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*5, 2)) as BINARY(2))) AS inventory5, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*6, 2)) as BINARY(2))) AS inventory6, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*7, 2)) as BINARY(2))) AS inventory7, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*8, 2)) as BINARY(2))) AS inventory8, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*9, 2)) as BINARY(2))) AS inventory9, 
CONVERT(INT,cast(reverse(substring(char_data, 305+16*10, 2)) as BINARY(2))) AS inventory10 
    ..........SO ON TO 64............. 
FROM CHAR_DATA0 
WHERE CHAR_KEY=10 

非常感謝你們。

- 編輯 -

我使用的是MSSQL

+0

爲什麼你會做一個查詢?在PHP \ JAVA \ C#中執行它,你使用的是什麼,這不應該是SQL的東西。 – gdoron

+1

看起來您需要將CHAR_DATA字段分解爲良好數據模型中的關係字段。所有編碼成一個字段的數據只是在尋求麻煩。 –

+1

查詢返回多少行?而不是64列和幾行,你可以使用64行和幾列(例如[inventoryN],[value])? – pilcrow

回答

0

我不認爲你可以不用動態SQL

declare @stmt nvarchar(max), @i int 

select @i = 1 

while @i <= 64 
begin 
    select 
     @stmt = 
      isnull(@stmt + ', ', '') + 
      'convert(int, cast(reverse(substring(char_data, 305+16*' + 
      cast(@i as nvarchar(10)) + ', 2)) as binary(2))) as inventory' + 
      cast(@i as nvarchar(10)) 

    select @i = @i + 1 
end 

select @stmt = 'select ' + @stmt + ' FROM CHAR_DATA0 WHERE [email protected]_KEY' 

exec dbo.sp_executesql 
    @stmt = @stmt, 
    @params = N'@CHAR_KEY int', 
    @CHAR_KEY = 10 
+0

這工作:)謝謝。 – user1553142

+0

它讓我在接受前等一分鐘。 :)對不起。它現在被接受。 – user1553142