sql字串變數拼接

2022-06-25 02:00:14 字數 1250 閱讀 7895

sql server拼接字串(字串中有變數)  總是忘記規律,**過來以幫助記憶。

一、拼接字串(整個字串不分割)步驟:

首先在字串的前後加單引號;

字串中的變數以'''+@para+'''在字串中表示;

若在執行時存在型別轉換錯誤,則應用相應的型別轉換函式,對變數進行型別轉換(如cast()函式)。

示例均採用northwind資料庫。

示例一:

包含sql拼接字串的儲存過程:

create procedure test

@testid  int

asdeclare @s nvarchar(800)

set @s='select * from dbo.categories where categoryid='''+cast(@testid as varchar)+''''

/* 我在使用中,這樣做時候,提示錯誤。*/

/*set @s='select * from dbo.categories where categoryid=cast('''+@testid+''' as varchar)' 這樣的話,才成功

*/print @s

exec(@s)

執行:exec  test  @testid=1

執行結果:

二、拼接字串(字串分割)步驟:

將不包含變數的字串前後用單引號括起來,

不含變數的字串與變數用+進行拼接

變數用''''+@para+''''進行表示(@para為變數名);

若執行儲存過程時出現型別轉換錯誤,則採用相應的型別轉換函式進行轉換。

示例採用northwind資料庫。

示例二:

包含sql 字串的儲存過程:

create procedure test

@testid  int

asdeclare @s nvarchar(800)

set @s='select * from dbo.categories where categoryid='+''''+cast(@testid as varchar)+''''

/*我按照下面寫法,才通過

set @s='select * from dbo.categories where categoryid=cast('+''''+@testid+''''+『 as varchar)』

print @s

exec(@s)

執行:exec  test  @testid=1

執行結果:

SQL 拼接字串

寫sql的時候有時候用到需要拼接多個字段或者在查詢出結果的字段裡加入一部分固定的字串。方法一 在查詢到的結果後,用 去拼接。這種方法就不在贅述。方法二 使用資料庫提供的方法concat a,b oracle 中concat a,b 只能有兩個引數,如果concat中連線的值不是字串,那麼oracle...

sql字串拼接

oracle 使用 或者concat sql select aaa bbb from dual aaa bbb aaabbb sql select concat aaa ccc from dual concat aaa aaaccc mysql中,使用 如果字串全是數字則轉化為數字,否則轉換為0,也...

sql字串拼接

在sql語句中經常需要進行字串拼接,以sqlserver,oracle,mysql三種資料庫為例,因為這三種資料庫具有代表性。sqlserver select 123 456 oracle select 123 456 from dual 或select concat 123 456 from du...