CSDN SQL版常見問題之四 行列互換

2021-05-08 03:34:47 字數 1428 閱讀 1263

--建立測試環境

create table test

(id int,

a int,

b int,

c int)

--插入資料

insert test select 1, 100, 90, 0

union all select 2, 80, 85, 92

union all select 3, 87, 0, 0

go--測試

--察看原表資料

select * from test

--如果列名已知

--寫出列名已知情況下的語句,是希望能幫助大家更好的理解動態sql語句

--下面exec(@s)中執行即為此語句

select * from (

select id, 'a' as type, a as score from test

union

select id, 'b' as type, b as score from test

union

select id, 'c' as type, c as score from test

) awhere

score != 0

order by

id, type

--如果type不是固定的,使用動態sql語句

--定義變數

declare @s varchar(8000)

--賦初值,此句不能少

select @s = ''

--從系統表syscolumns中迴圈得到列名(name),並使用name拼結語句

select @s = @s + ' union select id, ''' + name + ''' as type, ' + name + ' as score from test'

from syscolumns where id = object_id('test') order by colid

--去掉前面多於的union, 並去掉為0的score,加上排序

select @s = 'select * from (' + stuff(@s, 1, 7 ,'') + ' ) a where score != 0 order by id, type'

--執行動態sql語句

exec(@s)

go--刪除測試環境

drop table test

--結果

/*--表中原來資料

id a b c

1 100 90 0

2 80 85 92

3 87 0 0

--實現效果

id type score

1 a 100

1 b 90

2 a 80

2 b 85

2 c 92

3 a 87

*/ 

CSDN SQL版常見問題之二 行轉列

建立測試環境 create table test orderid int identity 1,1 id int,type varchar 10 score int 插入資料 insert test select 1,a 100 union all select 1,b 90 union all s...

ORACLE常見問題1000問 之四

174.all rows 表明對語句塊選擇基於開銷的優化方法,並獲得最佳吞吐量,使資源消耗最小化.例如 select all rows emp no,emp nam,dat in from bsempms where emp no ccbzzp 175.first rows 表明對語句塊選擇基於開銷...

SiteSucker mac版常見問題彙總!

sitesucker mac版常問問題解答 我可以將sitesucker與web 一起使用嗎?如果您的計算機受到防火牆的保護,則可能需要使用web 訪問 web 在 網路 首選項中設定。如果已配置了web sitesucker將自動將您的請求定向到指定的 伺服器。如果錯誤或警告未解決問題,則可能需要...