動態執行sql語句拼接字串select中帶有變數

時間 2021-10-17 05:11:04

1樓:在晴天的雨傘

--1. 構造使用in子句的動態transact-sql方法進行編號查詢

--a. 要查詢的欄位型別是數字型

--查詢的值列表

declare @idlist varchar(100)

set @idlist='1,2,3'

--拼接並執行動態transact-sql語句

exec('select * from tbname where fdname in('+@idlist+')')

go--b. 要查詢的欄位型別是字元型

--查詢的值列表已經加上了字串邊界符

declare @idlist varchar(100)

set @idlist='''a'',''b''''a'',''c'''

--拼接並執行動態transact-sql語句

exec('select * from tbname where fdname in('+@idlist+')')

go--查詢的值列表沒有字串邊界符

declare @idlist varchar(100)

set @idlist='a,b''a,c'

--由於是欄位型別是,所以在拼接時,必須為其加上字串邊界符(')

declare @s varchar(1000)

set @s=''''

+replace(replace(@idlist,'''',''''''),',',''',''')

+''''

--拼接並執行動態transact-sql語句

exec('select * from tbname where fdname in('+@s+')')

go--2. 使用like或者patindex進行編號查詢

--查詢的值列表

declare @idlist varchar(100)

set @idlist='1,2,3'

--查詢

select * from tbname where charindex(','+rtrim(fdname)+',',','+@idlist+',')>0

select * from tbname where patindex('%,'+rtrim(fdname)+',%',','+@idlist+',')>0

select * from tbname where ','+@idlist+',' like '%,'+rtrim(fdname)+',%'

go--3. 編號查詢中常見的錯誤

--a. 最容易犯的錯誤:表示式充當表示式列表。

declare @s varchar(100)

set @s='1'

select id,name from sysobjects where id in(@s)

/*--結果

id name

---------------- ------------

1 sysobjects

--*/

set @s='1,2,3'

select id,name from sysobjects where id in(@s)

/*--結果

伺服器: 訊息 245,級別 16,狀態 1,行 3

將 varchar 值 '1,2,3' 轉換為資料型別為 int 的列時發生語法錯誤。

--*/

go--b. 生成動態transact-sql語句時忽略了資料型別。

declare @s varchar(100)

set @s='u,s'

exec('select id,name from sysobjects where id in('+@s+')')

/*--結果:

伺服器: 訊息 207,級別 16,狀態 3,行 1

列名 's' 無效。

伺服器: 訊息 207,級別 16,狀態 1,行 1

列名 'u' 無效。

--*/

go--c. 忽略了比較的精確性問題。

--要查詢的資料

declare @t table(col varchar(10))

insert @t select '1'

union all select '11'

union all select '111'

union all select '22'

--查詢

declare @s varchar(100)

set @s='111,22'

select * from @t where charindex(col,@s)>0

/*--結果

col----------

1 11

11122 -*/go

2樓:匿名使用者

問題在第8行,

請參考第13行的寫法。

第8行要寫出 set @sql=@sql + n' select @i_i '

oracle中sql語句如何動態拼接

龍氏風采 sql code 在儲存過程裡面完成唄 例 create or replace procedure yyp cwdh table name varchar isstr sql varchar2 400 begin str sql select from table name where 1...

sql如何拆分符串,sql 如何 拆分 字串

with t as select id 8726c1554f4d428998949450d43bcc97,scno pi090001,orderno 3,contractitems 符合標準,printtitle 質量條款 as zd from dual select instr zd,1,1 su...

急救阿。。sql字串修改

你用什麼資料庫啊?sql server 資料庫 表名 table,工號字段 t1 獲取 select case when substring t1,1,1 b then 61 substring t1,2,1 substring t1,5,2 when substring t1,1,1 c then...