Reputation: 1
New to SQL scripting, trying to update part of a string in SQL script using define variable as below but can't get it to work. The column can be like \\OM-WD08-1\TestDoc\report\rep.pdf
there are lot of table with different column heading to update. I want to declare the variable and substitute where applicable. thanks in advance
USE MyServer
-- Declare the variable to be used.
DECLARE @OldPath varchar(30), @NewPath varchar(30)
-- Initialize the variable
SET @OldPath ='\\OM-WD08-1\';
SET @NewPath ='\\AA-PC\';
UPDATE AnatomyConfigs
SET Path = REPLACE(Path, @OldPath, @NewPath)
WHERE Path IS NOT NULL
AND Path LIKE @OldPath
GO
Upvotes: 0
Views: 77
Reputation: 239764
LIKE
only performs a literal match of text unless you include some form of wildcards (%
or _
). I would do this:
USE MyServer
-- Declare the variable to be used.
DECLARE @OldPath varchar(30), @NewPath varchar(30)
-- Initialize the variable
SET @OldPath ='\\OM-WD08-1\';
SET @NewPath ='\\AA-PC\';
UPDATE AnatomyConfigs
SET Path = @NewPath + SUBSTRING(Path,LEN(@OldPath)+1,8000)
WHERE Path LIKE @OldPath + '%'
GO
I prefer to use SUBSTRING
over REPLACE
because it more cleanly reflects "I just want to replace an instance that occurs at the start of the string". Now, given that no path should contain \\
s in the middle, this is not really required in this specific case, but I'm going for a more general answer.
Upvotes: 1
Reputation: 722
Declare @varibale_name varhcar(50)
To set Value:
set @variable_name='dgnughg'
update Table_Name set column_name=@variable_name
Upvotes: 0