开发者

How to do bulk update of views?

开发者 https://www.devze.com 2023-01-02 05:31 出处:网络
My database has about 30 views, most of which have a reference to another database on this server (call it DB1).

My database has about 30 views, most of which have a reference to another database on this server (call it DB1).

Now, without going into the reasons why, I need to update all those views to DB2开发者_Go百科, also on the local server.

I would hate to have to do this manually on each view. Is there some SQL query I can run that will replace all occurrences of the string 'DB1' with 'DB2' in all my views?


navigate to the views folder, press F7 (Object Explorer Details) now from the right pane select all the views you want, right click-->script view as--> DROP and CREATE TO --> new query window. In there change DB1 to DB2 and voila

see image

How to do bulk update of views?


You could query sys.sql_modules like this, which I'd use to generate a file via bcp (SSMS will truncate results) which can be run as another SQL script. This preserves permissions too.

I've used this technique before and it works.

SELECT
    REPLACE (REPLACE (sm.definition, 'CREATE VIEW', 'ALTER VIEW'), 'DB1.', 'DB2.') + '
    GO'
FROM
    sys.sql_modules sm
    JOIN
    sys.objects o ON sm.object_id = o.object_id
WHERE
    sm.definition LIKE '%DB1.%' AND o.type = 'V'
0

精彩评论

暂无评论...
验证码 换一张
取 消