How to do bulk update of views? - sql

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, 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

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'

Related

SQL create database if not exists, unexpected behaviour

I have a long stored procedure which begins with the following statement:
IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = N'DBNAME')
BEGIN
CREATE DATABASE [DBNAME]
END;
It is expected to create the DB on my local server, if it does not exist. The problem is that almost all of the time it goes thorugh this part of the stored procedure and does not create it, which then interferes with the other code from the same procedure. On the other hand, in very rare cases, it creates the DB. My question is: Is there a better way to check if the DB exists, because I have already tried at least 10.
Other ways I tried:
IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = N'DBNAME')
BEGIN
CREATE DATABASE [DBNAME]
END;
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'DBNAME')
BEGIN
CREATE DATABASE [DBNAME]
END;
IF NOT EXISTS (SELECT name FROM master.dbo.sys.databases WHERE name = N'DBNAME')
BEGIN
CREATE DATABASE [DBNAME]
END;
But if I run it outside of my sp, it works perfectly, which makes me think that it can be some problem related to permissions.
Try using
If(db_id(N'DBNAME') IS NULL)
If that does not work, it could be the permissions. That would explain why you are not getting an error message.
...minimum permissions required to see the corresponding row are
ALTER ANY DATABASE or VIEW ANY DATABASE server-level permission, or
CREATE DATABASE permission in the master database. The database to
which the caller is connected can always be viewed in sys.databases
(From sys.databases on MS documentation)
What permissions does the user under which you are running has?
Try changing your code to just return the contents of sys.databases so you can see it.
The issue appears to be a lack of 'GO' to terminate the statements. This does not work...
IF NOT EXISTS(SELECT 1 FROM sys.databases WHERE name='dba')
CREATE DATABASE [dba]
USE [dba]
But, this does...
IF NOT EXISTS(SELECT 1 FROM sys.databases WHERE name='dba')
CREATE DATABASE [dba]
GO
USE [dba]
Troy.
#
Chiming in because I had a similar issue: I wanted to create a database if it does not exist, then perform operations on that database.
I think the problem was that the script tried to run in one batch, so it tried to USE the database before the SQL server received the CREATE command.
This resulted in the whole script getting reverted and it seemed like the root of the issue was that the database never got created.
In my case the solution was to add a GO command after the initial part of the script where the table gets created but before I start working with it (e.g. creating tables).
When comparing strings use LIKE
if (SELECT count(name) FROM sys.databases WHERE name LIKE '%DBNAME%') = 0

identify insert stored proc

How do I identify stored proc that inserts records into "TableXYZ"?
I could have hundreds of stored procs.
Please help.
Use:
SELECT OBJECT_NAME(m.object_id), m.*
FROM SYS.SQL_MODULES m
WHERE m.definition like N'%INSERT INTO my_table_name%'
This will allow you to search for table reference(s).
Background:
SYSCOMMENTSand INFORMATION_SCHEMA.routines have NVARCHAR(4000) columns, while SYS.SQL_MODULES definition column is NVARCHAR(MAX). So if "my_table_name" is used at position 3998, it won't be found. SYSCOMMENTS does have multiple lines, but ROUTINES truncates.
I believe that you should be able to view the dependencies of the table by right clicking it on the management studio. This should at the very lease show you all stored procedures working with that table.
SELECT * FROM sys.sql_modules
WHERE definition like '%insert%TableXYZ%'
...gets you on the road to an answer.
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%insert into dbo.tablexyz%'
AND ROUTINE_TYPE='PROCEDURE'
You will need to adjust the like clause.
The add-in RedGate SQL Search, currently free, can be very helpful as it lets you search all of the code in your database. You could search for just the table name and see if that gets you close enough. If you consistently wrote your INSERT statement to look like INSERT INTO TableName, you could search for that entire phrase.
To do this kind of search manually as an T-SQL query, you can query the definition column in the sys.sql_modules system view. This provides you a lot of flexibility as you can use LIKE and/or PATINDEX to search for wildcards/patterns.

Where does SQL Server store the stored procedure code?

I once needed the lines of the stored procedures to be able to trace whether I have a reference to some function, procedure or table, or sometimes to try to find something inside of the sp's code.
Where does SQL Server store the procedure's code?
Use sys.sql_modules because definition is nvarchar(max) because it will not truncate long code.
In INFORMATION_SCHEMA.ROUTINES the ROUTINE_DEFINITION column is only nvarchar(4000) so if you try view the text of a long procedure and you will see that it is truncated.
Use this to search for text in any procedure, view, function:
SELECT DISTINCT
o.name AS Object_Name,o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o ON m.object_id=o.object_id
WHERE m.definition Like '%'+#Search+'%'
ORDER BY o.type_desc,o.name
use this to view the text of a given procedure, view, function:
select * from sys.sql_modules where object_id=object_id('YourProcedure')
You can use
select object_definition(object_id(routine_name)) from information_schema.routines
or
select object_definition(object_id) from sys.objects where name = 'foo'
or even
select object_definition(object_id('foo')); -- 'foo' is the table name
These versions are never truncated.
It stored it inside the system schema tables:
SELECT * FROM INFORMATION_SCHEMA.ROUTINES
See MSDN about the INFORMATION_SCHEMA.ROUTINES view:
ms-help://MS.SQLCC.v10/MS.SQLSVR.v10.en/s10de_6tsql/html/c75561b2-c9a1-48a1-9afa-a5896b6454cf.htm
For a content search on this, you can do the follwing:
SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%search_string%'
If you are just trying to view the stored procedures code you go into the progammabiltity folder within your DB and they should be all stored in there under stored procedures.
If you are trying to search for references to other objects, then you can run a query like this:
SELECT *
FROM syscomments
WHERE TEXT LIKE '%searchstring%'
This will return any objects in the database that reference the search string. You can then look at these objects to see what stored procedures (and views and functions) are doing so.
View Dependencies
In SQL Server Management Studio, right-click on a table, and choose "View Dependencies". You will see every object that references the table
INFORMATION_SCHEMA
The actual code for a stored proc, view, constraint, etc is stored in SysComments. You should query this using the views provided in the schema Information_Schema. Here are all the components of the Information_Schema.
If you use SQL Server Management Studion, you can right click on the database you want, then click "Tasks -> Generate Scripts".
There you can generate a script with all the SP's in one single file, separated files, or directly to a query window, and search/change what you want.
Hope this helps.
(this is for SQL Server 2008, but i think 2005 has this functionality too)
EDIT:
You can also see one single SP code, by following this path "YourDB -> Programmability -> Stored Procedures", then right click on the SP you want to see, and click "Modify", and a query window is opened with the code.

SQL Server 2005 search views for certain database objects

Is there a way in SQL Server to list all the views within a database that join from a particular object?
ie: find all the views that join from the table myTable
You can use sys.sql_dependencies:
select object_name(object_id),*
from sys.sql_dependencies
where referenced_major_id = object_id('<tablename>');
This will list all objects that depend on your table, you can restrict this to views by joining against sys.views:
select v.*
from sys.sql_dependencies d
join sys.views v on d.object_id = v.object_id
where referenced_major_id = object_id('<tablename>');
You have to search code and you have two options only. See comments below why other methods are not reliable.
select
object_name(m.object_id), m.*
from
sys.sql_modules m
where
m.definition like N'%my_view_name%'
or use OBJECT_DEFINITION
syscomments and INFORMATION_SCHEMA have nvarchar(4000) columns. So if "myViewName" is used at position 3998, it won't be found. syscomments does have multiple lines but ROUTINES truncates.
In SQL Server 2000, the sys.depends was unreliable, which affected "View dependencies" in the menus. I don't know if it's better in SQL 2005+. Example: view uses table, table is dropped and recreated, has different objectid, dependency = broken.
In SQL Server 2005, you can use a combination of sys.sql_dependencies and brute force parsing of the object text (as in gbn's answer). For more info on SQL Server 2005 dependencies, see http://msdn.microsoft.com/en-us/library/ms345449(SQL.90).aspx
In SQL Server 2008, there are new dependency DMVs and catalog views that are a bit more trustworthy than previous methods (sys.dm_sql_referenced_entities / sys.dm_sql_referencing_entities / sys.sql_expression_dependencies), but it is still easy to break them.
See this article for some ideas to make this work better. Also see http://msdn.microsoft.com/en-us/library/bb677168.aspx
Here's some of the examples from the link provided by unknown (in case that site disappears before stackoverflow does)
For SQL Server 2005, right click on the table name and select "View Dependencies"
A couple of the SQL only methods mentioned for SQL Server:
SELECT routine_name, routine_type FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%Employee%'
EXEC sp_depends #objname = N'HumanResources.Employee' ;

System Views text in SQL Server 2005

I am looking for viewing the text of the system views and procedures in SQL Server 2005 using the object explorer or using sp_helptext.
actually i am coming from the SQL Server 2000 background, where we have the feature of retreiving the code of the view and the stored procedure using SQL Server 2000 Enterprise manager directly, but still i am unable to find this feature in the SQL Server 2005 Management Studio and still looking for the same feature for getting the view and procedure text in SQL Server 2005.
Kindly please help me in this.
Do you have access to SQL Server Management Studio? It is now sys.sp_helptext and can be browsed at master --> Programmability --> Stored Procedures --> System Stored Procedures in the object browser and executed with
exec sys.sp_helptext ObjectName
All the information you are looking for can be found in the syscomments table which stores the definitions of all views, rules, defaults, triggers, CHECK constraints, DEFAULT constraints, and stored procedures. The SQL definition statements are stored in the "text" column.
select text from syscomments where id =
OBJECT_id('objectname')
order by colid
This Stackoverflow posting has a database reverse engineering script that (amongst other things) reverse engineers view definitions. From the script
-- This generates view definitions
--
select definition + char(10) + 'go' + char(10)
from sys.sql_modules c
join sys.objects o
on c.object_id = o.object_id
join #views o2
on o.object_id = o2.object_id
Note that #views is populated earlier in the script with a list of views to dump out. To select for a particular schema (also from the script)
select o.name
,o.object_id
into #views
from sys.objects o
join sys.schemas s
on s.schema_id = o.schema_id
where o.type in ('V')
and s.name = #schema
To get stored procedures, substitute 'P'; to get functions substitute 'FN' or 'TF'
In the master database the definitions for the system stored procedures live in sys.system_views, 'sys.system_objects, 'sys.system_columns, and sys.system_sql_modules. The queries in the reverse engineering script could be adapted fairly readily to get out the definitions of the system items by using these tables.
If you just want to see the text that defines a procedure:
Right click the stored procedure, and choose Modify. This will show the SQL that defines the stored procedure.
Or: right click, Script Stored Procedure as, CREATE To, New Query Editor Window.
The other answers are more advanced but I thought maybe you were asking a simple question :)
Here's how to list all the Dynamic Management Views:
SELECT * FROM sysobjects
WHERE name LIKE 'dm_%'
order by name
Unfortunately, if you run sp_helptext on these it doesn't give you much. For example,
exec sp_helptext N'sys.dm_os_sys_info'
Returns:
CREATE VIEW sys.dm_os_sys_info AS
SELECT *
FROM OpenRowset(TABLE SYSINFO)
All the ones I tried gave the same result.