when 4 then 1 when 5 then 2 when 1 then 3 when 2 then 4 when 3 then 5 end
2、 第二種
select * from torder by (id+2)%6
3、 第三種
select * from torder by charindex(cast(idas varchar),'45123')
4、 第四種
select * from tWHERE idbetween 0 and 5 order by charindex(cast(idas varchar),'45123')
5、 第五種
select * from torder by case when id>3 then id-5 else idend
6、 第六種
select * from torder by id/ 4 desc,idasc
一條語句刪除一批記錄 首先id列是int標識類類型,然后刪除ID值為5,6,8,9,10,11的列,這里的cast函數不能用convert函數代替,而且轉換的類型必須是varchar,而不能是char,否則就會執行出你不希望的結果,這里的"5,6,8,9,10,11"可以是你在頁面上獲取的一個chkboxlist構建成的值,然后用下面的一句就全部刪除了,比循環用多條語句高效吧應該。delete from [fujian] where charindex(','+cast([id] as varchar)+',',','+'5,6,8,9,10,11,'+',')>0 還有一種就是delete from table1where idin(1,2,3,4 )
---動態SQL基本語法:
1 :普通SQL語句可以用exec執行
Select * from tableNameexec('select * from tableName')exec sp_executesql N'select * from tableName' -- 請注意字符串前一定要加N
2:字段名,表名,數據庫名之類作為變量時,必須用動態SQL
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName-- 錯誤,不會提示錯誤,但結果為固定值FiledName,并非所要。exec('select' + @fname + ' from tableName')-- 請注意 加號前后的 單引號的邊上加空格
當然將字符串改成變量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName' --設置字段名
declare @s varchar(1000)
set @s = 'select' + @fname + ' from tableName' exec(@s)-- 成功
exec sp_executesql@s -- 此句會報錯
declare @s Nvarchar(1000)-- 注意此處改為nvarchar(1000)
set @s = 'select' + @fname + ' from tableName'
exec(@s)-- 成功
exec sp_executesql@s -- 此句正確
3. 輸出參數
declare @num int,@sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--如何將exec執行結果放入變量中?
declare @num int,@sqls nvarchar(4000)
set @sqls='select @a=count(*) from tableName'
exec sp_executesql@sqls,N'@a int output',
@num outputselect @num
1 :普通SQL語句可以用Exec執行 例:
Select * from tableNameExec('select * from tableName')Exec sp_executesql N'select * from tableName' -- 請注意字符串前一定要加N
select 中的case。select type,sum(case venderwhen 'A' then pcselse 0 end),sum(case venderwhen 'C' then pcselse 0 end),sum(case venderwhen 'B' then pcselse 0 end)FROM tablenamegroup by type 顯示結果: type vender pcs 電腦 A1 電腦 A1 光盤 B2 光盤 A2 手機 B3 手機 C3
23、說明:初始化表
table1TRUNCATE TABLE table1
24、說明:選擇從10到15的記錄
select top 5 * from (select top 15 * from table order by idasc) table_別名order by iddesc declare @a varchar(100),@b varchar(20)select @a='abcdefbcmnbcde',@b='bc' select (len(@a)-len(replace(@a,@b,'')))/len(@b)