如何在Microsoft SQL Server 2012已有数据的表字段中插入字符?
Can I insert a character into an existing string field in SQL Server 2012?
Absolutely! You can easily modify your string values—like converting 000032872634JFEO099 to 0-00032872634JFEO099—using SQL Server 2012's built-in STUFF() function. Here's a step-by-step breakdown of how to do it:
1. Test the transformation first (no data changes)
Before modifying your actual table data, verify the output with a SELECT query to ensure it matches what you want:
SELECT YourOriginalColumn, STUFF(YourOriginalColumn, 2, 0, '-') AS ModifiedColumn FROM YourTable;
Let me break down the STUFF() parameters for clarity:
- First value: The original string column you want to edit
- Second value: The position to start inserting (we use
2here to add the dash right after the first character) - Third value: Number of characters to delete from the original string (
0means we’re only inserting, not removing anything) - Fourth value: The character to insert (
'-'in this case)
2. Update your table data (permanent changes)
Once you’re confident the transformation works, you can update the actual table values. Critical: Always add a WHERE clause if you don’t want to update every row in the table!
UPDATE YourTable SET YourOriginalColumn = STUFF(YourOriginalColumn, 2, 0, '-') -- Optional: Filter to target specific rows (example below) WHERE YourOriginalColumn LIKE '0%'; -- Only updates values starting with '0'
Quick best practice
Before running an UPDATE on production data, it’s smart to:
- Double-check the SELECT results to confirm accuracy
- Back up your table or test on a staging copy to avoid accidental data loss
内容的提问来源于stack exchange,提问作者Danny Escalante
相关产品推荐
相关产品推荐

