How to grep SQL Server stored procedures? - sql-server

I would like to run a standard grep over all stored procedures in a given SQL Server database (assume 2005 or later). I have found a variety of simple queries to list the names of stored procedures containing a specific object, e.g.
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%table_I_want_to_find%'
But what I really want is, like grep, to list the specific lines in the identified stored procedures (so I do not have to manually open each one and see if it is what I am looking for).
I am open to solutions in T-SQL or PowerShell, or even an off-the-shelf utility.

Use SQL Search from Red Gate. It's a free tool and is fantastic.

I am brand new to SQL Server, but the following seems to work great and has proved itself to be quite useful already. I am using SQL Server 2008.
select ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_BODY, ROUTINE_DEFINITION
from INFORMATION_SCHEMA.ROUTINES
where ROUTINE_DEFINITION like '%searchtext%'
order by ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_DEFINITION;
For completeness, here are some similar queries you'll probably want to know about:
exec sp_help 'myTable'
select name
from sys.all_views
order by name;
select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE
from INFORMATION_SCHEMA.TABLES
order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE;
select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'myColumn'
order by TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME;

You could use SMO to dump the stored procedure DDL to files, and then use grep on them.
There are some examples of extracting the DDL here (called Scripting).

Related

List of available keywords for SQL Server

It seems I can't use SHOW command in SQL Server like SHOW COLUMNS FROM... or SHOW TABLES.
Is there somewhere a list of all the commands that are available so I know what I can use ?
To get Table and Column information
Select * From INFORMATION_SCHEMA.COLUMNS
Select * From INFORMATION_SCHEMA.Tables
Reserved Words
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql
Stripped and modified from a validation routine
Declare #Reserved table (Word varchar(100))
Insert Into #Reserved values
('ADD'),('ALL'),('ALTER'),('AND'),('ANY'),('AS'),('ASC'),('AUTHORIZATION'),('BACKUP'),('BEGIN'),('BETWEEN'),('BREAK'),('BROWSE'),('BULK'),('BY'),
('CASCADE'),('CASE'),('CHECK'),('CHECKPOINT'),('CLOSE'),('CLUSTERED'),('COALESCE'),('COLLATE'),('COLUMN'),('COMMIT'),('COMPUTE'),('CONSTRAINT'),
('CONTAINS'),('CONTAINSTABLE'),('CONTINUE'),('CONVERT'),('CREATE'),('CROSS'),('CURRENT'),('CURRENT_DATE'),('CURRENT_TIME'),('CURRENT_TIMESTAMP'),
('CURRENT_USER'),('CURSOR'),('DATABASE'),('DBCC'),('DEALLOCATE'),('DECLARE'),('DEFAULT'),('DELETE'),('DENY'),('DESC'),('DISK'),('DISTINCT'),
('DISTRIBUTED'),('DOUBLE'),('DROP'),('DUMP'),('ELSE'),('END'),('ERRLVL'),('ESCAPE'),('EXCEPT'),('EXEC'),('EXECUTE'),('EXISTS'),('EXIT'),('EXTERNAL'),
('FETCH'),('FILE'),('FILLFACTOR'),('FOR'),('FOREIGN'),('FREETEXT'),('FREETEXTTABLE'),('FROM'),('FULL'),('FUNCTION'),('GOTO'),('GRANT'),('GROUP'),
('HAVING'),('HOLDLOCK'),('IDENTITY'),('IDENTITY_INSERT'),('IDENTITYCOL'),('IF'),('IN'),('INDEX'),('INNER'),('INSERT'),('INTERSECT'),('INTO'),('IS'),
('JOIN'),('KEY'),('KILL'),('LEFT'),('LIKE'),('LINENO'),('LOAD'),('MERGE'),('NATIONAL'),('NOCHECK'),('NONCLUSTERED'),('NOT'),('NULL'),('NULLIF'),
('OF'),('OFF'),('OFFSETS'),('ON'),('OPEN'),('OPENDATASOURCE'),('OPENQUERY'),('OPENROWSET'),('OPENXML'),('OPTION'),('OR'),('ORDER'),('OUTER'),('OVER'),
('PERCENT'),('PIVOT'),('PLAN'),('PRECISION'),('PRIMARY'),('PRINT'),('PROC'),('PROCEDURE'),('PUBLIC'),('RAISERROR'),('READ'),('READTEXT'),('RECONFIGURE'),
('REFERENCES'),('REPLICATION'),('RESTORE'),('RESTRICT'),('RETURN'),('REVERT'),('REVOKE'),('RIGHT'),('ROLLBACK'),('ROWCOUNT'),('ROWGUIDCOL'),('RULE'),
('SAVE'),('SCHEMA'),('SECURITYAUDIT'),('SELECT'),('SEMANTICKEYPHRASETABLE'),('SEMANTICSIMILARITYDETAILSTABLE'),('SEMANTICSIMILARITYTABLE'),('SESSION_USER'),
('SET'),('SETUSER'),('SHUTDOWN'),('SOME'),('STATISTICS'),('SYSTEM_USER'),('TABLE'),('TABLESAMPLE'),('TEXTSIZE'),('THEN'),('TO'),('TOP'),('TRAN'),('TRANSACTION'),
('TRIGGER'),('TRUNCATE'),('TRY_CONVERT'),('TSEQUAL'),('UNION'),('UNIQUE'),('UNPIVOT'),('UPDATE'),('UPDATETEXT'),('USE'),('USER'),('VALUES'),('VARYING'),
('VIEW'),('WAITFOR'),('WHEN'),('WHERE'),('WHILE'),('WITH'),('WITHIN GROUP'),('WRITETEXT')
Select A.*
From INFORMATION_SCHEMA.COLUMNS A
Join #Reserved
on Column_Name = Word
The ISO standard is to query the INFORMATION_SCHEMA views for meta-data information. A more concise way is to list table/view columns in SQL Server is sp_help:
EXEC sp_help 'your-object-name-here';
In SSMS, you can highlight the desired object name in a query window and press ALT+F1 to execute sp_help for that object. With SQL Operations Studio, ALT-F12 will peek the object definition.
SELECT Distinct TABLE_NAME FROM information_schema.TABLES
Hope this helps and is similar for columns. Plus, I haven't seen any such list till now but surely will add in future once I see it.

How can I find tables name of selected database in MsSql

I want get tables name of specific Database in MsSql without
using db-name
something like this in mysqlIi need
select table_name from information_schema.tables where table_schema=db-name
how I can do it?
Instead of Table_schema use Table_catalog and you can prefix the DB-name before information_schema to get the tables in that database
SELECT *
FROM [db-name].information_schema.tables
WHERE TABLE_CATALOG = 'db-name'
Use UR_DBNAME
SELECT * FROM information_schema.tables
I believe this is the shortest version of what your are looking for
select name from [db_name].sys.tables

Text search in stored proc SQL Server

Does any one know the script to use for text search in SQL Server? I would like to search a text from all the stored proc inside the SQL Server, does anyone know what is the script I should use?
INFORMATION_SCHEMA.ROUTINES or syscomments are not reliable.
The text field is nvarchar(4000) for both (over multiple rows syscomments only). So your search text can be lost on the boundary for a syscomments or never found for INFORMATION_SCHEMA.ROUTINES
sys.sql_modules.definition is nvarchar(max)
SELECT
OBJECT_NAME(object_id)
FROM
sys.sql_modules
WHERE
definition LIKE '%mytext%'
Edit, Oct 2011
Bringing this answer up to date.
Red Gate SQL Search is a free SSMS plug in that is quite useful.
You can use as well:
select distinct object_name(id) from sys.syscomments where text like '%SearchTextHere%'
Updated: There are several equivalent ways. Here's one:
SELECT
OBJECT_NAME(object_id)
FROM
sys.sql_modules
WHERE
Definition LIKE '%searchtext%'
AND OBJECTPROPERTY(object_id, 'IsProcedure') = 1
Are you wanting to search for text through the stored procedures themselves?
Or table data?
If table data, how about LIKE?

Find all the varchar() fields in sql server?

Is it possible to find all the varchar() columns in my database?
I am using SQL Server 2008 and would like to get the list in SQL server management console.
JD.
Yep, this should work:
select * from INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE = 'varchar'
Try, this will give varchar and nvarchar, if the character_maximum_length column returns -1 then it is varchar(max) or nvarchar(max)
select * from
INFORMATION_SCHEMA.COLUMNS
where DATA_TYPE in('varchar','nvarchar')
Another method not limited to Views or User tables that utilizes sys objects instead of information_schema.
Multiple questions previously answered regarding usage of sys vs information_schema.
SELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'varchar' --you can change text to other datatypes
ORDER BY c.OBJECT_ID;
GO
Original source utilized for Sql Server 2005, just executed on Sql Server 2016.
Reference : Pinal Dave (https://blog.sqlauthority.com)
https://blog.sqlauthority.com/2007/08/09/sql-server-2005-list-all-the-column-with-specific-data-types/

Is there a succinct way to retrieve a list of table column names with T-SQL?

When I'm looking round a SQL Server database I often want to interactively retrieve a simple list of column names for a database table (no data type information etc., just the names) using sqlcmd.
I can do this:
EXEC sp_columns #table_name = 'tablename'
which gives me much more than I want and wraps in a command prompt to the extent that it is close to unintelligible, or I can do this:
SELECT col.name
FROM sysobjects obj
INNER JOIN syscolumns col
ON obj.id = col.id where obj.name = 'tablename'
which gives me what I want but is a bit verbose.
I'd like to be able to do something like this:
SELECT column_name
FROM (EXEC sp_columns #table_name = 'tablename')
but that doesn't work (see, for example, this question).
Is there a more succinct way to do this (i.e. one that is easier to type at the command line and therefore less error prone)?
Look at the ANSI-defined INFORMATION_SCHEMA views. Try SELECT * FROM INFORMATION_SCHEMA.COLUMNS for starters and go on from there.
Your example would require this SQL:
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'tablename'
SELECT [name] FROM sys.columns WHERE [object_id] = OBJECT_ID('MyTable')
Catalog views:
We recommend that you use catalog
views because they are the most
general interface to the catalog
metadata and provide the most
efficient way to obtain, transform,
and present customized forms of this
information. All user-available
catalog metadata is exposed through
catalog views.
Purely personal, but I don't like the INFORMATION_SCHEMA views

Resources