What is the query to backup the stored procedure of a database in SQL Server 2000?
In SQL Server 2000, you can use this query to list out the complete text of stored procedures, they can span multiple rows.
SELECT
o.name,o.id,o.xtype, c.colid, c.text
FROM dbo.sysobjects o
INNER JOIN dbo.syscomments c ON o.id = c.id
WHERE o.xtype = 'p'
ORDER BY o.Name,c.colid
I would be easier to use Enterprise Manager to script all the procedures though. In Enterprise Manager, right click on the database to you want to capture all the procedures from. An options list will pop-up, select "All Tasks" then "Generate SQL Script...". A dialogue box will appear, click on "show all", you can then refine the list of objects to script, by using the check boxes. Select the objects on the left side and click on the "Add>>" to move them to the script list. You can set formatting and other options, then click OK when done.
In SQl Server 2005+ you can use this query to list the complete text of all stored procedures, views and functions:
SELECT
LEFT(o.name, 100) AS Object_Name,o.type_desc,m.definition
FROM sys.sql_modules m
INNER JOIN sys.objects o ON m.object_id=o.object_id
you can take this output and save it if you like.
However, it is easier to use SQL Server management Studio to script out all procedures.
Related
sometimes I have completed the development of a solution on a development instance of a SQL database, after several test cycles, reworks, adjustments, etc.
When is time to move everything in production, I have to be sure that nothing is left behind by mistake (a trigger, a stored procedure).
One helper is to get a simple list of all the objects in the database.
A simple query to get the list of all the objects in your db is the following one:
select * from Sys.objects as o left join sys.schemas as s on o.schema_id = s.schema_id
where is_ms_shipped = 0
order by s.name, o.type, o.name
You can adjust it at your needs, remove fields, and so on.
Few notes:
I have excluded items delivered by Microsoft (is_ms_shipped)
I have joined the main system table with a catalogue of all the objects with the description of the schema. This is helpful to order all the elements
Using SSMS (SQL Server Management Studio), you can easily export the results in Excel, and work on it, add it to the documentation.
I have looked at the articles on stackoverflow about this issue.
I have also reviewed the article for calling stored procedures with parameters at https://www.c-sharpcorner.com/article/execute-sql-server-stored-procedure-with-user-parameter-in-power-bi/.
In my case, I have a stored procedure with no parameters.
I am unclear on how I would apply a fix-up to the M script in Power Query Editor to call a stored procedure with no parameters so that the stored procedure can be recognized and used by Power BI.
Could someone provide guidance for my scenario and steps below?
Scenario
I am using a Power BI with DirectQuery.
I need an ordered list or rows from my database. So I created a stored procedure in my SQL database that simply wraps a SQL SELECT statement with an ORDER BY clause.
The stored procedure has no parameters.
Steps
In SQL Server Management Studio, I create and test my stored procedure.
CREATE PROCEDURE [dbo].[pbiGetFileInfo]
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.CurrentReport.JobId AS CurrentJobId,
dbo.jobs.id AS JobId,
dbo.JobInstruments.Id AS JobInstrumentId,
dbo.JobInstruments.InstrumentDescription,
dbo.JobInstruments.Notes,
dbo.JobInstruments.Latitude,
dbo.JobInstruments.Longitude,
dbo.JobInstruments.Depth,
dbo.jobinstrumentimport.filename,
dbo.jobinstrumentimport.mindate AS FromDate,
dbo.jobinstrumentimport.maxdate AS ToDate,
DATEDIFF(hour, dbo.jobinstrumentimport.mindate, dbo.jobinstrumentimport.maxdate) AS duration_hours
FROM dbo.CurrentReport INNER JOIN
dbo.jobs ON dbo.CurrentReport.JobId = dbo.jobs.id INNER JOIN
dbo.JobInstruments ON dbo.jobs.id = dbo.JobInstruments.JobId INNER JOIN
dbo.jobinstrumentimport ON dbo.JobInstruments.Id = dbo.jobinstrumentimport.jobinstrumentid
ORDER BY JobInstruments.Id, FromDate
END
GO
In Power BI, I click the Transform Data button to launch the Power Query Editor.
Under queries, I right-click the first empty entry in the Queries pane and highlight the New Query item and click SQL Server from the context menu.
In the SQL Server Database dialog, I enter the Server and Database.
In the SQL Server Database dialog, I click the Advanced Options link to expand the dialog and show the SQL statement (optional, requires database) field.
In the SQL statement (optional, requires database), I enter EXEC [dbo].[pbiGetFileInfo] and click the OK button.
A truncated preview of the data returned by the stored procedure is displayed.
I click OK at the bottom of the preview.
A new entry Query1 appears in the Queries pane.
I right-click the new Query1 entry and rename it to pbiGetFileInfo. The M syntax that appears for the query at this point is:
= Sql.Database("Server Name", "NWBDatabase", [Query="EXEC [dbo].[pbiGetFileInfo]"])
At this point, if I click "Apply" from the Power Query Editor Ribbon, I will get the error message:
Incorrect syntax near the keyword 'EXEC'. Incorrect syntax near ')'
I click the Advanced Editor button on the toolbar. The M script for the pbiGetFileInfo query is:
let
Source = Sql.Database("Server Name", "NWBDatabase", [Query="EXEC [dbo].[pbiGetFileInfo]"])
in
Source
At this point, I am stuck.
My questions are:
The stored procedure has no parameters. Do I need to add a SQLSource prefix to the M script? If I do need a SQLSource, what would that look like?
let
SQLSource ...
let
Source = Sql.Database("Server Name", "NWBDatabase", [Query="EXEC [dbo].[pbiGetFileInfo]"])
in
Source
in
SQLSource
One thought is to create a view in SQL that calls the stored procedure. I have tried this and found that the view returns the same warning in Power BI as you would see if you tried to create a View with an ORDER BY in SQL. Calling views from Power BI is problematic at best.
Is there any way to write a stored procedure in SQL that minimizes the workarounds required to use them from Power BI?
Updates
I cannot call a stored procedure from Power BI under DirectQuery. It returns the same error `Incorrect syntax near 'EXEC' message. I need to see the DAX that is created to find the source of this error.
If I try the raw SQL Select from the stored procedure that I am trying to call, I get the following error:
Microsoft SQL: The ORDER BY clause is invalid in views.
Note: this is using straight SQL SELECT. The word VIEW is does not exist in the SQL SYNTAX at all.
A SQL Select that calls a VIEW only works if the calling outer SELECT contains a TOP (100) PERCENT clause. For example:
My view named [pbiGetFileInfo] contains the following SELECT statement:
SELECT dbo.CurrentReport.JobId AS CurrentJobId,
dbo.jobs.id AS JobId,
dbo.JobInstruments.Id AS JobInstrumentId,
dbo.JobInstruments.InstrumentDescription,
dbo.JobInstruments.Notes,
dbo.JobInstruments.Latitude,
dbo.JobInstruments.Longitude,
dbo.jobinstrumentimport.filename,
dbo.jobinstrumentimport.mindate AS FromDate,
dbo.jobinstrumentimport.maxdate AS ToDate,
DATEDIFF(hour, dbo.jobinstrumentimport.mindate, dbo.jobinstrumentimport.maxdate) AS duration_hours
FROM dbo.CurrentReport INNER JOIN
dbo.jobs ON dbo.CurrentReport.JobId = dbo.jobs.id INNER JOIN
dbo.JobInstruments ON dbo.jobs.id = dbo.JobInstruments.JobId INNER JOIN
dbo.jobinstrumentimport ON dbo.JobInstruments.Id = dbo.jobinstrumentimport.jobinstrumentid
The view itself does not contain an ORDER BY clause.
When I try to call this from a SQL SELECT statement:
SELECT * FROM [dbo].[pbiGetFileInfo] ORDER BY Id,FromDate
I get the error:
Microsoft SQL: The ORDER BY clause is invalid in views...
It works if I revise the SELECT to:
SELECT TOP (100) PERCENT * FROM [dbo].[pbiGetFileInfo] ORDER BY Id,FromDate
But, I am not sure it this will work correctly in Power BI DirectQuery.
My first thought is that Power BI seems to treat everything as a SQL VIEW. So all data sources are subject to the limitations of views. None of the advantages of sorting on a SQL Server are actually available in Power BI under DirectQuery. If you have to set the sort order in Power BI, there may be significant performance penalties.
I am experimenting with Table-Valued Functions (but have no faith that this will work in Power BI).
i am using below query to generate some information of around 7k lines. but the issue is that the query is taking too much time to complete just 7k line. i need to fine tune it.
select mo.CardUId,mo.CarParkUId,mo.PersonUId,mo.CardType,mo.CardNr,pk.LastName company_name,ab.Name carpark_name,
mo.ValidFrom,mo.ValidUntil,mo.LastTccTime,p.LastName customerName,mo.GroupName, mo.Name,p.Type,
mo.LastTccNr,mo.DisplayableCardCarrierNrId serialnr,mo.BlacklistEntry,
mo.GroupNumber from Person p
LEFT outer join vwAllCards mo on p.PersonUId=mo.PersonUId
left outer join Person pk on pk.PersonUId=p.CompanyDepartmentUId
left outer join CarPark ab on ab.CarParkUId=mo.CarParkUId
where p.Type=0 and mo.Name is not null
order by p.LastName
I use the SQL Profiler to auto create the indexes needed for a fine tune query.
Enter in SSMS (SQL Server Management Studio) -> Tools -> SQL Server Profiler.
Click Connect, and then click Run, to start a new trace.
Execute your slow query now, so the profiler can capture and record it.
Stop the query and File -> Save it.
In the menu, click Tools -> Database Engine Tuning advisor.
Click Connect when it opens, and in Workload, select file, and click the first button on the right (binoculars one). Then select the file you have just saved.
Select now the checkbox of your database, and click the "Start Analysis" button (below the "View" and "Action" menu).
Once it finish, open "Action" menu, and click in "Apply Recommendations".
Now you should have a fast and fine tuned query.
use with (nolock)
mo.GroupNumber from Person p with (nolock)
I have previously altered a table, added a column and modify a stored procedure.
I do not remember exactly which table and which stored procedure,
is there some log in sql management studio about what changes were done in a particular DB?
I have tried what is described here How to see query history in SQL Server Management Studio but i have not found the changes made to the DB
There's a few ways that you can get this information. Firstly you could try the standard reports --> Schema Changes History.
The information for this comes from:
SELECT cat.name AS Category
, b.name AS EventCaptured
, c.name AS ColumnCaptured
FROM fn_trace_geteventinfo(1) AS a
INNER JOIN sys.trace_events AS b
ON a.eventid = b.trace_event_id
INNER JOIN sys.trace_columns AS c
ON a.columnid = c.trace_column_id
INNER JOIN sys.trace_categories AS cat
ON b.category_id = cat.category_id
ORDER BY Category, EventCaptured, ColumnCaptured
Alternatively, query sys.traces to find the location of the default trace and feed this into fn_trace_gettable as per below.
SELECT *
FROM fn_trace_gettable
('C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\log.trc', default)
You can use Security\Server Audit Specification and enable DATABASE_OBJECT_CHANGE_GROUP audit on your database.
Use following reference in order to use SQL Server server audit.
CREATE SERVER AUDIT SPECIFICATION (Transact-SQL)
Create a Server Audit and Server Audit Specification
You can use the modify_date column in sys.objects table
SELECT *
FROM SYS.OBJECTS
WHERE Modify_Date BETWEEN <date_of_modification> AND <date_of_modification> + 1
and then you can try to narrow it down.
You can be even more specific and run the query for just tables and stored procedures.
SELECT *
FROM SYS.objects
WHERE TYPE IN ('IT', 'S', 'U', 'P', 'PC', 'X')
AND modify_date BETWEEN '10-Jun-2014' AND '11-Jun-2014'
I develop SSMSBoost add-in for SSMS and we have "Executed Query history" there. All actions are logged with timestamp, connection information and execution result. This will certainly only work, if you do all changes from SSMS with SSMSBoost installed. If someone will perform changes from other machine you will not see them, until he uses SSMSBoost as well and you share execution history.
I have been given access to a SQL Server database that is currently used by 3rd party app. As such, I don't have any documentation on how that application stores the data or how it retrieves it.
I can figure a few things out based on the names of various tables and the parameters that the user-defined functions takes and returns, but I'm still getting errors at every other turn.
I was thinking that it would be really helpful if I could see what the stored functions were doing with the parameters given to return the output. Right now all I've been able to figure out is how to query for the input parameters and the output columns.
Is there any built-in information_schema table that will expose what the function is doing between input and output?
If you can execute a query against your database somehow, and if you have the necessary permissions to read the system catalog views, then you could run this query to get the name, the definition (SQL code) and a few more bits of information about your functions:
SELECT
obj.name ,
obj.type ,
obj.type_desc ,
obj.create_date ,
obj.modify_date ,
m.definition ,
m.is_schema_bound
FROM
sys.objects obj
INNER JOIN
sys.sql_modules m ON obj.object_id = m.object_id
WHERE
obj.type IN ('AF', 'FN', 'FS', 'FT', 'IF', 'TF')
Provided you have appropriate permissions, you can simply script out all Stored Procedures and Functions:
Right-click on your database in SSMS (SQL Server Management Studio), select Tasks –> Generate Scripts, ensure your database is highlighted and click next. Ensure the options to script out Stored Procedures and Functions are selected.
You can install SSMS (client Tools) without requiring a SQL Server license.
Another way is sp_helptext which will show you the source of the passed SP or UDF;
sp_helptext fnBlaDeBla