简体   繁体   中英

Trigger (possibly stored procedure) to replace text when a new record is inserted?

I am running into a snag. An application we've developed allows users to create links to files, but the links are being created relative to the server the SQL database resides on, not relative to the user.

This is some pseudocode of what I need to happen.

when dbo.File_.Link_to_File has a prefix of '\\dc\App Share'
replace '\\dc\App Share' with 'Z:'

Essentially the file links are being stored relative to the server ( \\\\dc\\App Share ), but I have mapped this as a network drive (Z:) on all of the users' computers. I need a trigger that will replace the server path prefix with Z:

Keep in mind this is the prefix (path) to a file ( \\\\dc\\App Share\\myfolder\\myfile.txt ), so the code needs to find just this prefix and replace it.

This is running on SQL Server 2008 R2.

Any help is appreciated. Thanks much!

I don't know why companies insist on using transient mapped drives instead of UNC paths, but this should work...

UPDATE
    dbo.File_
SET
    Link_to_File = 'Z:' + SUBSTRING(Link_to_File, 15, LEN(Link_to_File) - 14)
WHERE
    Link_to_File LIKE '\\dc\App Share%'

By the way, if you're looking for a to make sure that the data is correct going forward, then you should put that logic in your application. Ideally, your application already uses stored procedures to update the data, so you can add code similar to the above to update the incoming parameter that holds the Link_to_File. Something like:

IF (@Link_to_File LIKE '\\dc\App Share%')
    SET @Link_to_File = 'Z:' + SUBSTRING(Link_to_File, 15, LEN(Link_to_File) - 14)
CREATE TRIGGER File_Insert ON dbo.File
INSTEAD OF INSERT
AS
DECLARE @LinkColumn varchar(50)
SET @LinkColumn = (SELECT Link_to_File FROM INSERTED)
IF (LEFT(@LinkColumn, 1) <> 'Z')
BEGIN
     SELECT * INTO #Inserted FROM Inserted
     UPDATE #Inserted SET Link_to_File = REPLACE(Link_to_File,'\\dc\App Share','Z:')
     INSERT INTO dbo.File_ SELECT * FROM #Inserted
END
ELSE
     INSERT INTO dbo.File_SELECT * FROM Inserted

I don't have any way to test this. Replace database with the db name, table with your table name and urlcolumn with your column name

CREATE TRIGGER trigger_name ON database.table
INSTEAD OF INSERT
AS
DECLARE @UriColumn varchar(150)
SET @UriColumn = (SELECT urlcolumn FROM INSERTED)
IF (@UriColumn like '\\dc\App Share' + '%')
BEGIN
     SET @UriColumn = replace(@UriColumn, '\\dc\App Share', 'Z:'
     SELECT * INTO #Inserted FROM Inserted
     UPDATE #Inserted SET urlcolumn = @UriColumn
     INSERT INTO table SELECT * FROM #Inserted
END
ELSE
     INSERT INTO table SELECT * FROM Inserted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM