Search text in stored procedure in SQL Server - sql

I want to search a text from all my database stored procedures. I use the below SQL:
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 '%[ABD]%';
I want to search for [ABD] in all stored procedures including square brackets, but it's not giving the proper result. How can I change my query to achieve this?

Escape the square brackets:
...
WHERE m.definition Like '%\[ABD\]%' ESCAPE '\'
Then the square brackets will be treated as a string literals not as wild cards.

Try this request:
Query
SELECT name
FROM sys.procedures
WHERE Object_definition(object_id) LIKE '%strHell%'

Have you tried using some of the third party tools to do the search? There are several available out there that are free and that saved me a ton of time in the past.
Below are two SSMS Addins I used with good success.
ApexSQL Search – Searches both schema and data in databases and has additional features such as dependency tracking and more…
SSMS Tools pack – Has same search functionality as previous one and several other cool features. Not free for SQL Server 2012 but still very affordable.
I know this answer is not 100% related to the questions (which was more specific) but hopefully others will find this useful.

I usually run the following to achieve that:
select distinct object_name(id)
from syscomments
where text like '%[ABD]%'
order by object_name(id)

Good practice to work with SQL Server.
Create below stored procedure and set short key,
CREATE PROCEDURE [dbo].[Searchinall]
(#strFind AS VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
--TO FIND STRING IN ALL PROCEDURES
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) SP_Name
,OBJECT_DEFINITION(OBJECT_ID) SP_Definition
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+#strFind+'%'
END
--TO FIND STRING IN ALL VIEWS
BEGIN
SELECT OBJECT_NAME(OBJECT_ID) View_Name
,OBJECT_DEFINITION(OBJECT_ID) View_Definition
FROM sys.views
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+#strFind+'%'
END
--TO FIND STRING IN ALL FUNCTION
BEGIN
SELECT ROUTINE_NAME Function_Name
,ROUTINE_DEFINITION Function_definition
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%'+#strFind+'%'
AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY
ROUTINE_NAME
END
--TO FIND STRING IN ALL TABLES OF DATABASE.
BEGIN
SELECT t.name AS Table_Name
,c.name AS COLUMN_NAME
FROM sys.tables AS t
INNER JOIN sys.columns c
ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%'+#strFind+'%'
ORDER BY
Table_Name
END
END
Now - Set short key as below,
So next time whenever you want to find a particular text in any of the four objects like Store procedure, Views, Functions and Tables. You just need to write that keyword and press shortcut key.
For example: I want to search 'PaymentTable' then write 'PaymentTable' and make sure you select or highlight the written keyword in query editor and press shortcut key ctrl+4 - it will provide you full result.

Redgate's SQL Search is a great tool for doing this, it's a free plugin for SSMS.

Please take this as a "dirty" alternative but this saved my behind many times especially when I was not familiar with the DB project. Sometimes you are trying to search for a string within all SPs and forget that some of the related logic may have been hiding between Functions and Triggers or it can be simply worded differently than you thought.
From your MSSMS you may right click your DB and select
Tasks -> Generate Scripts wizard to output all the SPs, Fns and Triggers into a single .sql file.
Make sure to select Triggers too!
Then just use Sublime or Notepad to search for the string you need to find. I know this may be quite inefficient and paranoid approach but it works :)

You can also use this one:
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION like '%Search_String%'

select top 10 * from
sys.procedures
where object_definition(object_id) like '%\[ABD\]%'

It might help you!
SELECT DISTINCT
A.NAME AS OBJECT_NAME,
A.TYPE_DESC
FROM SYS.SQL_MODULES M
INNER JOIN SYS.OBJECTS A ON M.OBJECT_ID = A.OBJECT_ID
WHERE M.DEFINITION LIKE '%['+#SEARCH_TEXT+']%'
ORDER BY TYPE_DESC

Also you can use:
SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE '%flags.%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)
Thats include comments

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 '%[String]%';

SELECT DISTINCT OBJECT_NAME([id]),[text]
FROM syscomments
WHERE [id] IN (SELECT [id] FROM sysobjects WHERE xtype IN
('TF','FN','V','P') AND status >= 0) AND
([text] LIKE '%text to be search%' )
OBJECT_NAME([id]) --> Object Name (View,Store Procedure,Scalar Function,Table function name)
id (int) = Object identification number
xtype char(2) Object type. Can be one of the following object types:
FN = Scalar function
P = Stored procedure
V = View
TF = Table function

SELECT name , type_desc , create_date , modify_date
FROM sys.procedures
WHERE Object_definition(object_id) LIKE '%High%'

I created a procedure to search text in procedures/functions, tables, views, or jobs. The first parameter #search is the search criterion, #target the search target, i.e., procedures, tables, etc. If not specified, search all. #db is to specify the database to search, default to your current database. Here is my query in dynamic SQL.
ALTER PROCEDURE [dbo].[usp_find_objects]
(
#search VARCHAR(255),
#target VARCHAR(255) = NULL,
#db VARCHAR(35) = NULL
)
AS
SET NOCOUNT ON;
DECLARE #TSQL NVARCHAR(MAX), #USEDB NVARCHAR(50)
IF #db <> '' SET #USEDB = 'USE ' + #db
ELSE SET #USEDB = ''
IF #target IS NULL SET #target = ''
SET #TSQL = #USEDB + '
DECLARE #search VARCHAR(128)
DECLARE #target VARCHAR(128)
SET #search = ''%' + #search + '%''
SET #target = ''' + #target + '''
IF #target LIKE ''%Procedure%'' BEGIN
SELECT o.name As ''Stored Procedures''
FROM SYSOBJECTS o
INNER JOIN SYSCOMMENTS c ON o.id = c.id
WHERE c.text LIKE #search
AND o.xtype IN (''P'',''FN'')
GROUP BY o.name
ORDER BY o.name
END
ELSE IF #target LIKE ''%View%'' BEGIN
SELECT o.name As ''Views''
FROM SYSOBJECTS o
INNER JOIN SYSCOMMENTS c ON o.id = c.id
WHERE c.text LIKE #search
AND o.xtype = ''V''
GROUP BY o.name
ORDER BY o.name
END
/* Table - search table name only, need to add column name */
ELSE IF #target LIKE ''%Table%'' BEGIN
SELECT t.name AS ''TableName''
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE #search
ORDER BY TableName
END
ELSE IF #target LIKE ''%Job%'' BEGIN
SELECT j.job_id,
s.srvname,
j.name,
js.step_id,
js.command,
j.enabled
FROM [msdb].dbo.sysjobs j
JOIN [msdb].dbo.sysjobsteps js
ON js.job_id = j.job_id
JOIN master.dbo.sysservers s
ON s.srvid = j.originating_server_id
WHERE js.command LIKE #search
END
ELSE BEGIN
SELECT o.name As ''Stored Procedures''
FROM SYSOBJECTS o
INNER JOIN SYSCOMMENTS c ON o.id = c.id
WHERE c.text LIKE #search
AND o.xtype IN (''P'',''FN'')
GROUP BY o.name
ORDER BY o.name
SELECT o.name As ''Views''
FROM SYSOBJECTS o
INNER JOIN SYSCOMMENTS c ON o.id = c.id
WHERE c.text LIKE #search
AND o.xtype = ''V''
GROUP BY o.name
ORDER BY o.name
SELECT t.name AS ''Tables''
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE #search
ORDER BY Tables
SELECT j.name AS ''Jobs''
FROM [msdb].dbo.sysjobs j
JOIN [msdb].dbo.sysjobsteps js
ON js.job_id = j.job_id
JOIN master.dbo.sysservers s
ON s.srvid = j.originating_server_id
WHERE js.command LIKE #search
END
'
EXECUTE sp_executesql #TSQL
Update:
If you renamed a procedure, it only updates sysobjects but not syscomments, which keeps the old name and therefore that procedure will not be included in the search result unless you drop and recreate the procedure.

also try this :
SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION like '%\[ABD\]%'

A different version, To make query more appropriate for different coding practices.
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 UPPER(M.DEFINITION) LIKE UPPER('%Your Text%');

Using CHARINDEX:
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 CHARINDEX('[ABD]',m.definition) >0 ;
Using PATINDEX:
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 PATINDEX('[[]ABD]',m.definition) >0 ;
Using this double [[]ABD] is similar to escaping :
WHERE m.definition LIKE '%[[]ABD]%'

This query is search text in stored procedure from all databases.
DECLARE #T_Find_Text VARCHAR(1000) = 'Foo'
IF OBJECT_ID('tempdb..#T_DBNAME') IS NOT NULL DROP TABLE #T_DBNAME
IF OBJECT_ID('tempdb..#T_PROCEDURE') IS NOT NULL DROP TABLE #T_PROCEDURE
CREATE TABLE #T_DBNAME
(
IDX int IDENTITY(1,1) PRIMARY KEY
, DBName VARCHAR(255)
)
CREATE TABLE #T_PROCEDURE
(
IDX int IDENTITY(1,1) PRIMARY KEY
, DBName VARCHAR(255)
, Procedure_Name VARCHAR(MAX)
, Procedure_Description VARCHAR(MAX)
)
INSERT INTO #T_DBNAME (DBName)
SELECT name FROM master.dbo.sysdatabases
DECLARE #T_C_IDX INT = 0
DECLARE #T_C_DBName VARCHAR(255)
DECLARE #T_SQL NVARCHAR(MAX)
DECLARE #T_SQL_PARAM NVARCHAR(MAX)
SET #T_SQL_PARAM =
' #T_C_DBName VARCHAR(255)
, #T_Find_Text VARCHAR(255)
'
WHILE EXISTS(SELECT TOP 1 IDX FROM #T_DBNAME WHERE IDX > #T_C_IDX ORDER BY IDX ASC)
BEGIN
SELECT TOP 1
#T_C_DBName = DBName
FROM #T_DBNAME WHERE IDX > #T_C_IDX ORDER BY IDX ASC
SET #T_SQL = ''
SET #T_SQL = #T_SQL + 'INSERT INTO #T_PROCEDURE(DBName, Procedure_Name, Procedure_Description)'
SET #T_SQL = #T_SQL + 'SELECT SPECIFIC_CATALOG, ROUTINE_NAME, ROUTINE_DEFINITION '
SET #T_SQL = #T_SQL + 'FROM ' + #T_C_DBName + '.INFORMATION_SCHEMA.ROUTINES '
SET #T_SQL = #T_SQL + 'WHERE ROUTINE_DEFINITION LIKE ''%''+ #T_Find_Text + ''%'' '
SET #T_SQL = #T_SQL + 'AND ROUTINE_TYPE = ''PROCEDURE'' '
BEGIN TRY
EXEC SP_EXECUTESQL #T_SQL, #T_SQL_PARAM, #T_C_DBName, #T_Find_Text
END TRY
BEGIN CATCH
SELECT #T_C_DBName + ' ERROR'
END CATCH
SET #T_C_IDX = #T_C_IDX + 1
END
SELECT IDX, DBName, Procedure_Name FROM #T_PROCEDURE ORDER BY DBName ASC

Select distinct OBJECT_NAME(id) from syscomments where text like '%string%' AND OBJECTPROPERTY(id, 'IsProcedure') = 1

/*
SEARCH SPROCS & VIEWS
The following query will allow search within the definitions
of stored procedures and views.
It spits out the results as XML, with the full definitions,
so you can browse them without having to script them individually.
*/
/*
STEP 1: POPULATE SEARCH KEYS. (Set to NULL to ignore)
*/
DECLARE
#def_key varchar(128) = '%foo%', /* <<< definition search key */
#name_key varchar(128) = '%bar%', /* <<< name search key */
#schema_key varchar(128) = 'dbo'; /* <<< schema search key */
;WITH SearchResults AS (
/*
STEP 2: DEFINE SEARCH QUERY AS CTE (Common Table Expression)
*/
SELECT
[Object].object_id AS [object_id],
[Schema].name AS [schema_name],
[Object].name AS [object_name],
[Object].type AS [object_type],
[Object].type_desc AS [object_type_desc],
[Details].definition AS [module_definition]
FROM
/* sys.sql_modules = where the body of sprocs and views live */
sys.sql_modules AS [Details] WITH (NOLOCK)
JOIN
/* sys.objects = where the metadata for every object in the database lives */
sys.objects AS [Object] WITH (NOLOCK) ON [Details].object_id = [Object].object_id
JOIN
/* sys.schemas = where the schemas in the datatabase live */
sys.schemas AS [Schema] WITH (NOLOCK) ON [Object].schema_id = [Schema].schema_id
WHERE
(#def_key IS NULL OR [Details].definition LIKE #def_key) /* <<< searches definition */
AND (#name_key IS NULL OR [Object].name LIKE #name_key) /* <<< searches name */
AND (#schema_key IS NULL OR [Schema].name LIKE #schema_key) /* <<< searches schema */
)
/*
STEP 3: SELECT FROM CTE INTO XML
*/
/*
This outer select wraps the inner queries in to the <sql_object> root element
*/
SELECT
(
/*
This inner query maps stored procedure rows to <procedure> elements
*/
SELECT TOP 100 PERCENT
[object_id] AS [#object_id],
[schema_name] + '.' + [object_name] AS [#full_name],
[module_definition] AS [module_definition]
FROM
SearchResults
WHERE
object_type = 'P'
ORDER BY
[schema_name], [object_name]
FOR XML
PATH ('procedure'), TYPE
) AS [procedures], /* <<< as part of the outer query,
this alias causes the <procedure> elements
to be wrapped within the <procedures> element */
(
/*
This inner query maps view rows to <view> elements
*/
SELECT TOP 100 PERCENT
[object_id] AS [#object_id],
[schema_name] + '.' + [object_name] AS [#full_name],
[module_definition] AS [module_definition]
FROM
SearchResults
WHERE
object_type = 'V'
ORDER BY
[schema_name], [object_name]
FOR XML
PATH ('view'), TYPE
) AS [views] /* <<< as part of the outer query,
this alias causes the <view> elements
to be wrapped within the <views> element */
FOR XML
PATH ('sql_objects')

Every so often I use this script to figure out which procs to modify, or to figure out what uses a column of a table, or that table at all to remove some old junk. It checks each database on the instance it is ran on by the wonderfully supplied sp_msforeachdb.
if object_id('tempdb..##nothing') is not null
drop table ##nothing
CREATE TABLE ##nothing
(
DatabaseName varchar(30),
SchemaName varchar(30),
ObjectName varchar(100),
ObjectType varchar(50)
)
EXEC master.sys.sp_msforeachdb
'USE ?
insert into ##nothing
SELECT
db_name() AS [Database],
[Scehma]=schema_name(o.schema_id),
o.Name,
o.type
FROM sys.sql_modules m
INNER JOIN sys.objects o
ON o.object_id = m.object_id
WHERE
m.definition like ''%SOME_TEXT%'''
--edit this text
SELECT * FROM ##nothing n
order by OBJECTname

-- Applicable for SQL 2005+
USE YOUR_DATABASE_NAME //;
GO
SELECT [Scehma] = schema_name(o.schema_id)
,o.NAME
,o.type
FROM sys.sql_modules m
INNER JOIN sys.objects o ON o.object_id = m.object_id
WHERE m.DEFINITION LIKE '%YOUR SEARCH KEYWORDS%'
GO

This search routine is based on https://stackoverflow.com/a/33631029/2735286 and contains the schema name too in the search results:
CREATE PROCEDURE [dbo].[Searchinall] (#strFind AS VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
--TO FIND STRING IN ALL PROCEDURES
BEGIN
SELECT s.name SP_Schema_Name, OBJECT_NAME(p.OBJECT_ID) SP_Name
,OBJECT_DEFINITION(p.OBJECT_ID) SP_Definition
FROM sys.procedures p
INNER JOIN sys.schemas s on p.schema_id = s.schema_id
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+#strFind+'%'
END
--TO FIND STRING IN ALL VIEWS
BEGIN
SELECT s.name SP_Schema_Name, OBJECT_NAME(OBJECT_ID) View_Name
,OBJECT_DEFINITION(OBJECT_ID) View_Definition
FROM sys.views v
INNER JOIN sys.schemas s on v.schema_id = s.schema_id
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+#strFind+'%'
END
--TO FIND STRING IN ALL FUNCTION
BEGIN
SELECT ROUTINE_SCHEMA, ROUTINE_NAME Function_Name
,ROUTINE_DEFINITION Function_definition
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%'+#strFind+'%'
AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY
ROUTINE_NAME
END
--TO FIND STRING IN ALL TABLES OF DATABASE.
BEGIN
SELECT s.name SP_Schema_Name, t.name AS Table_Name
,c.name AS COLUMN_NAME
FROM sys.tables AS t
INNER JOIN sys.columns c
ON t.OBJECT_ID = c.OBJECT_ID
INNER JOIN sys.schemas s on t.schema_id = s.schema_id
WHERE c.name LIKE '%'+#strFind+'%'
ORDER BY
Table_Name
END
END
Here is how you use it:
execute [dbo].[Searchinall] 'cust'
Here is an alternative which lists all objects with a specific keyword in one single query:
SELECT DISTINCT
s.name AS Schema_Name,
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
INNER JOIN sys.schemas s on o.schema_id = s.schema_id
WHERE m.definition Like '%dim_forex%' ESCAPE '\' order by 3;
This query should return the same results and the procedure call in this answer.

You can also use
CREATE PROCEDURE [Search](
#Filter nvarchar(max)
)
AS
BEGIN
SELECT name
FROM procedures
WHERE definition LIKE '%'+#Filter+'%'
END
and then run
exec [Search] 'text'

Related

Dynamically stating FROM which table name to SELECT from

Would it be possible to use a system query to retrieve TABLE name and then SELECT * FROM that TABLE name. Along the lines of:
SELECT * FROM CAST (( SELECT TOP 1 t.Name
FROM sys.tables t
JOIN sys.columns c ON c.OBJECT_ID = t.OBJECT_ID
WHERE c.NAME = 'SomeColumnID' ) AS sys.tables )
The current issue is that the SELECT TOP 1 t.Name will return a string and could it be then cast into a valid Tables.Name.
You need dynamic sql for this: that is, build a query string from a query, then execute it with sp_executesql.
For your use case, that would look like:
declare #q nvarchar(max);
select top (1) #q = N'select * from ' + t.name
from sys.tables t
join sys.columns c on c.object_id = t.object_id
where c.name = 'SomeColumnID'
-- debuug the query
select #q sql;
-- execute the query
execute sp_executesql #q;

Find text in my tables, stored procedures, and views in SQL Server

I am able to search for specific text in my views and stored procedure, but I'm not able to search through my tables at the same time.
Here is what I have:
DECLARE #cmd VARCHAR(1000),
#search_string VARCHAR(200)
CREATE TABLE #temp
(
[Database_Name] sysname,
[Schema_Name] sysname,
[Object_Name] sysname,
[Object_Type] nvarchar(60)
)
-- Set the search string
SET #search_string = 'text'
SET #cmd = 'INSERT INTO #temp SELECT DISTINCT ''?'', s.name AS Schema_Name, 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 INNER JOIN [?].sys.schemas s ON o.schema_id = s.schema_id WHERE m.definition Like ''%' + #search_string + '%'''
-- Uncomment the following if you have problems with your command and want to see the command
--PRINT #cmd
-- Run for every database on the server
EXEC sp_MSforeachdb #cmd
-- Retrieve your results from the temp table
SELECT *
FROM #temp
ORDER BY [Database_Name], [Object_Name], [Object_Type]
-- If you want to omit certain databases from your results, simply add
-- the appropriate WHERE clause, as in the following:
--SELECT *
--FROM #temp
--WHERE db NOT IN ('DB1', 'DB4', 'DB7')
--ORDER BY db, obj_type, obj_name
DROP TABLE #temp
Please try this query for column search
SELECT
t.[name] TableName
, c.[name] ColumnName
FROM sys.columns c
INNER JOIN sys.tables t on t.object_id = c.object_id
WHERE t.[type] = 'U'
AND c.[name] LIKE '%Text%'
Below script will get result for all the databases for both Tables and other obejcts. Hope this will help.
DECLARE #command varchar(1000)
DECLARE #SearchWord VARCHAR(20) = 'Text'
CREATE TABLE #Search (DatabaseName VARCHAR(255),SchemaName VARCHAR(50),ObjectName VARCHAR(255),ObjectType VARCHAR(50))
SET #command = 'USE ? INSERT INTO #Search
SELECT DB_NAME(), SCHEMA_NAME(t.schema_id),t.[name] TableName, ''Table'' FROM sys.columns c INNER JOIN sys.tables t on t.object_id = c.object_id WHERE t.[type] = ''U'' AND c.[name] LIKE ' + '''%' + #SearchWord + '%'''
EXEC sp_MSforeachdb #command;
SET #command = 'USE ? INSERT INTO #Search
SELECT DISTINCT DB_Name(),s.name AS Schema_Name, 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 INNER JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE m.definition Like ''%' + #SearchWord + '%'''
EXEC sp_MSforeachdb #command
SELECT * FROM #Search;
DROP TABLE #Search
There is an easy way
select
object= object_name(c.id), o.name , o.type
from sys.syscomments as c
join sys.objects as o on c.id = o.object_id
where c.text like '%Id%'
All compiled objects are in sys.comments, the name changed a few times depending on the version of SQL you have, the sample is from the current version.
Now, one doesn't need to join sys.object as the TSQL is in the text column.
You can look for any string that you have used, table names, field names or code comments. the sample shows %ID% looking for all function, trigger, views procedures that have something that contains the letters ID.
You know that when clicking on an object in SSMS you can select show Dependencies right?

SQL Column Name wildcard

I have a table with 30+ fields and I want to quickly narrow my selection down to all fields where column name start with 'Flag'.
select * Like Flag% from Table1
You will want to build a dynamic query as explained here: https://stackoverflow.com/a/4797728/9553919
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Foods'
AND table_schema = 'YourDB'
AND column_name LIKE 'Vegetable%'
This SQL Statement should be useful. You may be able to simplify it but it does work.
Edit2: I just now saw your pervasive-sql tag. Unfortunately I've never worked with that and don't know if the syntax is compatible with MS SQL Server. I'll let my answer here in case it helps others, but wanted to share that I tested this using SQL Server.
Edit: SCHEMA_NAME function isn't necessary. You can replace SCHEMA_NAME(schema_id) with the name of your schema in single quotes if you want, but either will work.
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM
sys.tables AS t
INNER JOIN
sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE
t.name = 'Table1' AND
c.name Like 'Flag%'
ORDER BY
c.name
or
SELECT t.name AS table_name,
'MySchema' AS schema_name,
c.name AS column_name
FROM
sys.tables AS t
INNER JOIN
sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE
t.name = 'Table1' AND
c.name Like 'Flag%'
ORDER BY
c.name
To do this, you will need to query the system tables for the columns associated to the table and filter them to what you want. From there, place them into a variable table and create a CSV of columns. From there, you can dynamically construct your query as needed. The below example should help you get started.
DECLARE #tableName VARCHAR(100) = 'dbo.SomeTable'
DECLARE #columnNames TABLE
(
Id INT IDENTITY PRIMARY KEY,
ColumnName VARCHAR(100)
)
--Grabs all of the columns into a variable table
INSERT INTO #columnNames (ColumnName)
SELECT
[name]
FROM sys.columns
WHERE
[object_id] = OBJECT_ID(#tableName)
AND
[name] LIKE '%Flag'
DECLARE #columns VARCHAR(1000)
--Creates a CSV of columns
SET #columns =
STUFF(
(
SELECT
',' + ColumnName
FROM #columnNames
FOR XML PATH(''))
,1,1,'')
DECLARE #selectStatement NVARCHAR(4000) = CONCAT('SELECT ', #columns, ' FROM ', #tableName)
PRINT #selectStatement
EXEC #selectStatement

Use a Query to access column description in SQL

I am trying to access the Column description properties using the INFORMATION_SCHEMA
I have created this Query in the past to get the column name but i can not figure out how to get description of the column
SELECT COLUMN_NAME AS Output, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)
This is where the Description is on the field properties
If by 'description' you mean 'Description' displayed in SQL Management Studio in design mode, here it is:
select
st.name [Table],
sc.name [Column],
sep.value [Description]
from sys.tables st
inner join sys.columns sc on st.object_id = sc.object_id
left join sys.extended_properties sep on st.object_id = sep.major_id
and sc.column_id = sep.minor_id
and sep.name = 'MS_Description'
where st.name = #TableName
and sc.name = #ColumnName
If you specifically want to use INFORMATION_SCHEMA (as I was) then the following query should help you obtain the column's description field:
SELECT COLUMN_NAME AS [Output]
,ORDINAL_POSITION
,prop.value AS [COLUMN_DESCRIPTION]
FROM INFORMATION_SCHEMA.TABLES AS tbl
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS col ON col.TABLE_NAME = tbl.TABLE_NAME
INNER JOIN sys.columns AS sc ON sc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND sc.NAME = col.COLUMN_NAME
LEFT JOIN sys.extended_properties prop ON prop.major_id = sc.object_id
AND prop.minor_id = sc.column_id
AND prop.NAME = 'MS_Description'
WHERE tbl.TABLE_NAME = #TableName
The fn_listextendedproperty system function will do what you're looking for.
It’s also referred to as sys.fn_listextendedproperty.
Syntax is as follows:
fn_listextendedproperty (
{ default | 'property_name' | NULL }
, { default | 'level0_object_type' | NULL }
, { default | 'level0_object_name' | NULL }
, { default | 'level1_object_type' | NULL }
, { default | 'level1_object_name' | NULL }
, { default | 'level2_object_type' | NULL }
, { default | 'level2_object_name' | NULL }
)
Example Usage: Lists extended properties for all columns of the ScrapReason table in the Production schema
USE AdventureWorks2012;
GO
SELECT objtype, objname, name, value
FROM fn_listextendedproperty (NULL, 'schema', 'Production', 'table', 'ScrapReason', 'column', NULL);
GO
sp_helptext will not work since it can't be used for tables as per TechNet.
Displays the definition of a user-defined rule, default, unencrypted
Transact-SQL stored procedure, user-defined Transact-SQL function,
trigger, computed column, CHECK constraint, view, or system object
such as a system stored procedure.
sp_columns does not return the sys.extended_properties.value field which you're looking for.
fn_listextendedproperty is arguably easier to work with and more generic than the query in the accepted answer.
exec sp_columns #Tablename... That's the system stored procedure that will give you the info.
Other than that, here is a post with a lot of good information on the INFORMATION SCHEMA views: What is the equivalent of 'describe table' in SQL Server?
If you want to have table with table schema, table name, column name and description you can use following query:
select TableName = tbl.table_schema + '.' + tbl.table_name,
sc.name [Column],
sep.value [Description]
from sys.tables st
inner join information_schema.tables tbl on st.object_id=object_id(tbl.table_schema + '.' + tbl.table_name)
inner join sys.columns sc on st.object_id = sc.object_id
left join sys.extended_properties sep on st.object_id = sep.major_id
and sc.column_id = sep.minor_id
and sep.name = 'MS_Description'
This will generate follwing table:
Table name
Column name
Description
dbo.VersionInfo
AppliedOn
Description
I wanted to generate the md file in my CI/CD pipeline and for this purpose I created a PowerShell module. It has Out-Md switch which generates MD file with all descriptions.
Get-ColumnsDescription -Verbose -ServerInstance ".\SQL2019" -Database PTMeetings -OutMD
To cover topic completely:
If you would like to add the description with the query you can use
EXEC sys.sp_addextendedproperty
#name=N'MS_Description' --name of property
,#value=N'Age should be between 12 and 100 Descp' --descption text
,#level0type=N'SCHEMA'
,#level0name=N'jl' --Schema name
,#level1type=N'TABLE'
,#level1name=N'JournalItemNotes' --Table Name
,#level2type=N'COLUMN'
,#level2name=N'NotesType' -- Column Name
And if You are interested in the idempotent function I propose to create procedure:
IF OBJECT_ID ('dbo.usp_addorupdatedescription', 'P') IS NOT NULL
DROP PROCEDURE dbo.usp_addorupdatedescription;
GO
CREATE PROCEDURE usp_addorupdatedescription
#table nvarchar(128), -- table name
#column nvarchar(128), -- column name, NULL if description for table
#descr sql_variant -- description text
AS
BEGIN
SET NOCOUNT ON;
DECLARE #c nvarchar(128) = NULL;
IF #column IS NOT NULL
SET #c = N'COLUMN';
BEGIN TRY
EXECUTE sp_updateextendedproperty N'MS_Description', #descr, N'SCHEMA', N'dbo', N'TABLE', #table, #c, #column;
END TRY
BEGIN CATCH
EXECUTE sp_addextendedproperty N'MS_Description', #descr, N'SCHEMA', N'dbo', N'TABLE', #table, #c, #column;
END CATCH;
END
GO
Are you looking for the information in the sys.extended_properties view?
https://stackoverflow.com/a/15008885/1948904

Query to list SQL Server stored procedures along with lines of code for each procedure

I want a query that returns a list of all the (user) stored procedures in a database by name, with the number of lines of code for each one.
i.e.
sp_name lines_of_code
-------- -------------
DoStuff1 120
DoStuff2 50
DoStuff3 30
Any ideas how to do this?
select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc
from
(
select o.name as sp_name,
(len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code,
case when o.xtype = 'P' then 'Stored Procedure'
when o.xtype in ('FN', 'IF', 'TF') then 'Function'
end as type_desc
from sysobjects o
inner join syscomments c
on c.id = o.id
where o.xtype in ('P', 'FN', 'IF', 'TF')
and o.category = 0
and o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams')
) t
group by t.sp_name, t.type_desc
order by 1
Edited so it should also now work in SQL Server 2000- 2008 and to exclude Database Diagram-related sprocs and funcs (which appear like user created objects).
FWIW, here's another one:
SELECT o.type_desc AS ROUTINE_TYPE
,QUOTENAME(s.[name]) + '.' + QUOTENAME(o.[name]) AS [OBJECT_NAME]
,(LEN(m.definition) - LEN(REPLACE(m.definition, CHAR(10), ''))) AS LINES_OF_CODE
FROM sys.sql_modules AS m
INNER JOIN sys.objects AS o
ON m.[object_id] = o.[OBJECT_ID]
INNER JOIN sys.schemas AS s
ON s.[schema_id] = o.[schema_id]
This works for MS-SQL 2000
SET NOCOUNT ON
DECLARE #ProcName varchar(100)
DECLARE #LineCount int
DECLARE C CURSOR LOCAL FOR
SELECT o.name as ProcName FROM sysobjects o WHERE (o.xtype = 'P') ORDER BY o.name
OPEN C
CREATE TABLE #ProcLines ([Text] varchar(1000))
FETCH NEXT FROM C INTO #ProcName
WHILE ##FETCH_STATUS = 0
BEGIN
DELETE FROM #ProcLines
INSERT INTO #ProcLines EXEC('sp_helptext ' + #ProcName + '')
SELECT #LineCount = COUNT(*) FROM #ProcLines
PRINT #ProcName + ' Lines: ' + LTRIM(STR(#LineCount))
FETCH NEXT FROM C INTO #ProcName
END
CLOSE C
DEALLOCATE C
DROP TABLE #ProcLines
select * from sysobjects where type = 'p'