目錄
Syntax of STUFF
1. Basic Example: Replacing Characters
2. Inserting Text Without Deleting
3. Removing Characters (Delete Without Inserting)
4. Practical Use Case: Formatting Credit Card Numbers
Key Notes and Tips
Common Pitfalls
首頁 資料庫 SQL 如何在SQL中使用該功能進行字符串操作?

如何在SQL中使用該功能進行字符串操作?

Aug 28, 2025 am 05:47 AM
sql STUFF函数

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,適用於需按位置精確操作字符串的場景。

How to use the STUFF function for string manipulation in SQL?

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.

How to use the STUFF function for string manipulation in SQL?

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 or length 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:

How to use the STUFF function for string manipulation in SQL?
 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.

How to use the STUFF function for string manipulation in SQL?

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 from start , 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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Stock Market GPT

Stock Market GPT

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

如何將列與SQL中的多個值進行比較? 如何將列與SQL中的多個值進行比較? Sep 16, 2025 am 02:12 AM

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

如何在SQL中使用Soundex函數進行語音搜索? 如何在SQL中使用Soundex函數進行語音搜索? Sep 21, 2025 am 01:54 AM

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

如何在SQL中的表或列中添加註釋? 如何在SQL中的表或列中添加註釋? Sep 21, 2025 am 05:22 AM

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

SQL中的子查詢和CTE有什麼區別? SQL中的子查詢和CTE有什麼區別? Sep 16, 2025 am 07:47 AM

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

如何在SQL表中找到孤兒記錄? 如何在SQL表中找到孤兒記錄? Sep 17, 2025 am 04:51 AM

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

如何在SQL中執行非Equi加入? 如何在SQL中執行非Equi加入? Sep 16, 2025 am 07:37 AM

Anon-EquijoinusesComparisonOperatorsLikeBetB​​​​etBetBetBetBetBetbetables.2.ISUISUSEFULFORFORRANGECOMPARISONSSSSSSUCHASSALASALAYORDATERANGES.3.SYNTAXINVOLVOLVOLVOLVOLVOLVOLVESSPECIFEDCONTIFENSINSINSIN CLACEINCLAUSE,E.G.

如何在SQL中獲得給定日期的一個月的最後一天? 如何在SQL中獲得給定日期的一個月的最後一天? Sep 18, 2025 am 12:57 AM

使用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中的表中更新數據 如何在SQL中的表中更新數據 Sep 18, 2025 am 06:04 AM

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

See all articles