December 19, 2014 at 11:00 pm
Hello all,
So I have the following column named String in a table:
<key>Children</key><integer>2</integer>
This of course can vary for the different records. What's the best way to replace the 2 with the contents of my variable with TSQL?
declare @children int
set @children = 4
I want to do something like this:
SELECT <key>Children</key><integer>@children</integer>
Thanks,
Strick
December 20, 2014 at 3:31 am
Quick simple suggestion
😎
USE tempdb;
GO
SET NOCOUNT ON;
DECLARE @SAMPLE_DATA TABLE(TSTR VARCHAR(100) NOT NULL);
INSERT INTO @SAMPLE_DATA(TSTR)
VALUES ('<key>Children</key><integer>2</integer>')
,('<key>Children</key><integer>123</integer>')
,('<key>Children</key><integer></integer>')
;
DECLARE @children INT = 4;
SELECT
SD.TSTR
,SUBSTRING(SD.TSTR,1,(CHARINDEX('<integer>',SD.TSTR,1) + LEN('<integer>') - 1 ))
+ CONVERT(VARCHAR(12),@children,0)
+ SUBSTRING(SD.TSTR,CHARINDEX('</integer>',SD.TSTR,1),LEN(SD.TSTR)) AS OUT_STR
FROM @SAMPLE_DATA SD;
Results
TSTR OUT_STR
------------------------------------------ ----------------------------------------
<key>Children</key><integer>2</integer> <key>Children</key><integer>4</integer>
<key>Children</key><integer>123</integer> <key>Children</key><integer>4</integer>
<key>Children</key><integer></integer> <key>Children</key><integer>4</integer>
December 22, 2014 at 4:17 pm
Here's an alternative:
declare @children int
set @children = 4
SELECT
string,
STUFF(string, start_of_integer_value, CHARINDEX('<', string, start_of_integer_value) - start_of_integer_value,
CAST(@children AS varchar(10)))
FROM (
SELECT '<key>Children</key><integer>2</integer>' AS string UNION ALL
SELECT '<key>Children</key><integer>123</integer>' UNION ALL
SELECT '<key>Children</key><integer></integer>'
) AS test_data
CROSS APPLY (
SELECT CHARINDEX('<integer>', string) + 9 AS start_of_integer_value
) AS assign_alias_name
SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".
December 22, 2014 at 6:12 pm
Heh... a better way to do it would be to get that nasty ol' denormalized junk known as XML out of your database and replace it with proper columns and data. 😉
--Jeff Moden
Change is inevitable... Change for the better is not.
December 29, 2014 at 2:09 pm
Thanks everyone for your responses. This helped.
Strick
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply