SQL递增查询

时间:2012-11-21 17:56:04

标签: sql sql-server

我有这个查询。所有选择在技术上都是相同的,只是乘数上的递增值。我需要这个达到* 64。

关于如何以比我现在更有效的方式做到这一点的任何建议?

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

1 个答案:

答案 0 :(得分: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 CHAR_KEY=@CHAR_KEY'

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