如何在SQL中使用該功能進行字符串操作?
STUFF函數用於刪除字符串中指定位置和長度的字符並插入新字符,1. 例如STUFF('123-456-7890', 5, 3, 'XXX')返回'123-XXX-7890';2. 通過設置長度為0可實現插入,如STUFF('Hello World', 6, 0, 'Beautiful ')返回'Hello Beautiful World';3. 使用空字符串替換可刪除字符,如STUFF('abcdef', 2, 3, '')返回'af';4. 可嵌套使用進行複雜格式化,如為信用卡號加空格返回'1234 5678 9012 3456',該函數基於1索引,參數為NULL或索引無效時返回NULL,適用於需按位置精確操作字符串的場景。
The STUFF
function in SQL is a powerful string manipulation tool that allows you to delete a specified number of characters from a string and then insert another set of characters at a given position . It's particularly useful when you need precise control over modifying parts of a string.

Syntax of STUFF
STUFF(input_string, start, length, replacement_string)
- input_string : The original string you want to modify.
- start : The position (1-based index) where deletion begins.
- length : The number of characters to delete from the start position.
- replacement_string : The string to insert at the start position after deletion.
⚠️ If
start
orlength
is NULL,STUFF
returns NULL. Also, positions are 1-indexed.
1. Basic Example: Replacing Characters
Suppose you have a phone number and want to mask part of it:

SELECT STUFF('123-456-7890', 5, 3, 'XXX') AS ModifiedNumber;
Result: 123-XXX-7890
- Starts at position 5 (
'4'
in'123-456-7890'
) - Deletes 3 characters (
'456'
) - Inserts
'XXX'
in their place
This is commonly used for data anonymization or formatting.

2. Inserting Text Without Deleting
You can use STUFF
to insert text by setting length
to 0:
SELECT STUFF('Hello World', 6, 0, 'Beautiful ') AS InsertedText;
Result: Hello Beautiful World
- Starts at position 6 (just before
'W'
) - Deletes 0 characters
- Inserts
'Beautiful '
This is a clever way to insert text at a specific point without removing anything.
3. Removing Characters (Delete Without Inserting)
To delete part of a string without inserting anything, use an empty string as the replacement:
SELECT STUFF('abcdef', 2, 3, '') AS RemovedChars;
Result: af
- Starts at position 2 (
'b'
) - Deletes 3 characters (
'bcd'
) - Inserts nothing
Useful for cleaning up unwanted substrings when you know their position.
4. Practical Use Case: Formatting Credit Card Numbers
Imagine you want to format a 16-digit card number with spaces every 4 digits:
DECLARE @CardNumber VARCHAR(16) = '1234567890123456'; SELECT STUFF(STUFF(STUFF(@CardNumber, 5, 0, ' '), 10, 0, ' '), 15, 0, ' ') AS FormattedCard;
Result: 1234 5678 9012 3456
- Each
STUFF
inserts a space at positions 5, 10, and 15 - Since
length = 0
, no characters are deleted
This shows how STUFF
can be nested for complex formatting.
Key Notes and Tips
- Position is 1-based , not 0-based like many programming languages.
- If
start
is greater than the length of the string,STUFF
returns NULL. - If
start
is 0, it also returns NULL — always use valid positions. - If
length
exceeds available characters fromstart
, it removes up to the end. -
STUFF
works only on string types (VARCHAR
,NVARCHAR
,CHAR
, etc.)
Common Pitfalls
- ❌ Using 0-based indexing:
STUFF('abc', 0, 1, 'x')
→ returns NULL - ❌ Invalid lengths:
STUFF('abc', 2, -1, 'x')
→ invalid, length must be ≥ 0 - ❌ Forgetting that replacement happens after deletion, not before
In short, STUFF
gives you surgical control over string modification — delete and insert in one step. While REPLACE
is good for known substrings, STUFF
shines when you know the position and length of the part you want to change.
Basically, if you need to splice strings by position, STUFF
is your go-to function in SQL Server.
以上是如何在SQL中使用該功能進行字符串操作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

使用IN操作符可高效比較列與多個值,如SELECT*FROMemployeesWHEREdepartment_idIN(1,2,3);排除多個值則用NOTIN,但需注意NULL影響結果。

SOUNDEX函數將文本轉換為表示發音的四字符代碼,首字母加三位數字,忽略元音和特定字母,相似發音的輔音映射到相同數字,實現基於發音的搜索。例如Smith和Smythe均生成S530,可通過WHERESOUNDEX(last_name)=SOUNDEX('Smith')查詢發音相近的姓名。結合DIFFERENCE函數可返回0到4的相似度評分,篩選發音接近的結果,適用於處理拼寫差異,但對非英語名稱效果有限,且需注意性能優化。

UseCOMMENTONCOLUMNorALTERTABLEwithCOMMENTtodocumenttablesandcolumnsinSQL;syntaxvariesbyDBMS—PostgreSQLandOracleuseCOMMENTON,MySQLusesCOMMENTinCREATE/ALTERstatements,andcommentscanbeviewedviasystemtableslikeINFORMATION_SCHEMA,butSQLitelackssupport.

子查詢是嵌套在另一查詢中的查詢,適用於簡單一次性計算,可位於SELECT、FROM或WHERE子句中;2.CTE通過WITH子句定義,提升複雜查詢的可讀性,支持遞歸和多次引用;3.子查詢適合單次使用,CTE更適用於需清晰結構、重複使用或遞歸的場景。

Tofindorphanedrecords,useaLEFTJOINorNOTEXISTStoidentifychildrecordswithoutmatchingparentrecords.Forexample,SELECTo.FROMOrdersoLEFTJOINCustomerscONo.customer_id=c.customer_idWHEREc.customer_idISNULLreturnsorderslinkedtonon-existentcustomers.Alternativ

Anon-EquijoinusesComparisonOperatorsLikeBetBetBetBetBetBetBetbetables.2.ISUISUSEFULFORFORRANGECOMPARISONSSSSSSUCHASSALASALAYORDATERANGES.3.SYNTAXINVOLVOLVOLVOLVOLVOLVOLVESSPECIFEDCONTIFENSINSINSIN CLACEINCLAUSE,E.G.

使用LAST_DAY()函數(MySQL、Oracle)可直接獲取指定日期所在月的最後一天,如LAST_DAY('2023-10-15')返回2023-10-31;2.SQLServer使用EOMONTH()函數實現相同功能;3.PostgreSQL通過DATE_TRUNC與INTERVAL計算月末;4.SQLite利用date函數結合'startofmonth'、' 1month'和'-1day'獲取結果。

要更新SQL表中的數據,需使用UPDATE語句,其基本語法為:UPDATE表名SET列1=值1,列2=值2...WHERE條件;1.更新單行時,通過WHERE子句指定唯一標識符,如主鍵;2.更新多列時,在SET子句中列出多個列和值;3.更新多行時,WHERE條件匹配的多條記錄將被同時更新;4.若省略WHERE子句,則所有行都會被更新,需謹慎操作;5.建議使用事務包裹UPDATE操作,以便在出錯時回滾;此外,應始終先用SELECT測試條件、備份重要數據,並在支持的數據庫中使用LIMIT限制更新行數
