I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out.
Source: http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1313431,00.html
Works with SQL2000,2005,2008
USE master;
GO
IF OBJECT_ID('dbo.sp_SDS', 'P') IS NOT NULL
DROP PROCEDURE dbo.sp_SDS;
GO
CREATE PROCEDURE dbo.sp_SDS
#TargetDatabase sysname = NULL, -- NULL: all dbs
#Level varchar(10) = 'Database', -- or "File"
#UpdateUsage bit = 0, -- default no update
#Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes
AS
/**************************************************************************************************
**
** author: Richard Ding
** date: 4/8/2008
** usage: list db size AND path w/o SUMmary
** test code: sp_SDS -- default behavior
** sp_SDS 'maAster'
** sp_SDS NULL, NULL, 0
** sp_SDS NULL, 'file', 1, 'GB'
** sp_SDS 'Test_snapshot', 'Database', 1
** sp_SDS 'Test', 'File', 0, 'kb'
** sp_SDS 'pfaids', 'Database', 0, 'gb'
** sp_SDS 'tempdb', NULL, 1, 'kb'
**
**************************************************************************************************/
SET NOCOUNT ON;
IF #TargetDatabase IS NOT NULL AND DB_ID(#TargetDatabase) IS NULL
BEGIN
RAISERROR(15010, -1, -1, #TargetDatabase);
RETURN (-1)
END
IF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_CombinedInfo;
IF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_DbFileStats;
IF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_ValidDbs;
IF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL
DROP TABLE dbo.##Tbl_Logs;
CREATE TABLE dbo.##Tbl_CombinedInfo (
DatabaseName sysname NULL,
[type] VARCHAR(10) NULL,
LogicalName sysname NULL,
T dec(10, 2) NULL,
U dec(10, 2) NULL,
[U(%)] dec(5, 2) NULL,
F dec(10, 2) NULL,
[F(%)] dec(5, 2) NULL,
PhysicalName sysname NULL );
CREATE TABLE dbo.##Tbl_DbFileStats (
Id int identity,
DatabaseName sysname NULL,
FileId int NULL,
FileGroup int NULL,
TotalExtents bigint NULL,
UsedExtents bigint NULL,
Name sysname NULL,
FileName varchar(255) NULL );
CREATE TABLE dbo.##Tbl_ValidDbs (
Id int identity,
Dbname sysname NULL );
CREATE TABLE dbo.##Tbl_Logs (
DatabaseName sysname NULL,
LogSize dec (10, 2) NULL,
LogSpaceUsedPercent dec (5, 2) NULL,
Status int NULL );
DECLARE #Ver varchar(10),
#DatabaseName sysname,
#Ident_last int,
#String varchar(2000),
#BaseString varchar(2000);
SELECT #DatabaseName = '',
#Ident_last = 0,
#String = '',
#Ver = CASE WHEN ##VERSION LIKE '%9.0%' THEN 'SQL 2005'
WHEN ##VERSION LIKE '%8.0%' THEN 'SQL 2000'
WHEN ##VERSION LIKE '%10.0%' THEN 'SQL 2008'
END;
SELECT #BaseString =
' SELECT DB_NAME(), ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE ''Data'' END'
ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-text'' ELSE ''reserved'' END' END +
', name, ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END +
', size*8.0/1024.0 FROM ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END +
' WHERE '
+ CASE WHEN #Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc = ''ONLINE''' END + '';
SELECT #String = 'INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM ' +
CASE WHEN #Ver = 'SQL 2000' THEN 'master.dbo.sysdatabases'
WHEN #Ver IN ('SQL 2005', 'SQL 2008') THEN 'master.sys.databases'
END + ' WHERE HAS_DBACCESS(name) = 1 ORDER BY name ASC';
EXEC (#String);
INSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');
-- For data part
IF #TargetDatabase IS NOT NULL
BEGIN
SELECT #DatabaseName = #TargetDatabase;
IF #UpdateUsage <> 0 AND DATABASEPROPERTYEX (#DatabaseName,'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (#DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT #String = 'USE [' + #DatabaseName + '] DBCC UPDATEUSAGE (0)';
PRINT '*** ' + #String + ' *** ';
EXEC (#String);
PRINT '';
END
SELECT #String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + #BaseString;
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + #DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
EXEC ('USE [' + #DatabaseName + '] ' + #String);
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = #DatabaseName;
END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
SELECT TOP 1 #DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname > #DatabaseName ORDER BY Dbname ASC;
IF ##ROWCOUNT = 0
BREAK;
IF #UpdateUsage <> 0 AND DATABASEPROPERTYEX (#DatabaseName, 'Status') = 'ONLINE'
AND DATABASEPROPERTYEX (#DatabaseName, 'Updateability') <> 'READ_ONLY'
BEGIN
SELECT #String = 'DBCC UPDATEUSAGE (''' + #DatabaseName + ''') ';
PRINT '*** ' + #String + '*** ';
EXEC (#String);
PRINT '';
END
SELECT #Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;
SELECT #String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + #BaseString;
EXEC ('USE [' + #DatabaseName + '] ' + #String);
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)
EXEC ('USE [' + #DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = #DatabaseName WHERE Id BETWEEN #Ident_last + 1 AND ##IDENTITY;
END
END
-- set used size for data files, do not change total obtained from sys.database_files as it has for log files
UPDATE dbo.##Tbl_CombinedInfo
SET U = s.UsedExtents*8*8/1024.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s
ON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;
-- set used size and % values for log files:
UPDATE dbo.##Tbl_CombinedInfo
SET [U(%)] = LogSpaceUsedPercent,
U = T * LogSpaceUsedPercent/100.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l
ON l.DatabaseName = t.DatabaseName
WHERE t.type = 'Log';
UPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;
UPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;
IF UPPER(ISNULL(#Level, 'DATABASE')) = 'FILE'
BEGIN
IF #Unit = 'KB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T * 1024, U = U * 1024, F = F * 1024;
IF #Unit = 'GB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T / 1024, U = U / 1024, F = F / 1024;
SELECT DatabaseName AS 'Database',
type AS 'Type',
LogicalName,
T AS 'Total',
U AS 'Used',
[U(%)] AS 'Used (%)',
F AS 'Free',
[F(%)] AS 'Free (%)',
PhysicalName
FROM dbo.##Tbl_CombinedInfo
WHERE DatabaseName LIKE ISNULL(#TargetDatabase, '%')
ORDER BY DatabaseName ASC, type ASC;
SELECT CASE WHEN #Unit = 'GB' THEN 'GB' WHEN #Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM dbo.##Tbl_CombinedInfo;
END
IF UPPER(ISNULL(#Level, 'DATABASE')) = 'DATABASE'
BEGIN
DECLARE #Tbl_Final TABLE (
DatabaseName sysname NULL,
TOTAL dec (10, 2),
[=] char(1),
used dec (10, 2),
[used (%)] dec (5, 2),
[+] char(1),
free dec (10, 2),
[free (%)] dec (5, 2),
[==] char(2),
Data dec (10, 2),
Data_Used dec (10, 2),
[Data_Used (%)] dec (5, 2),
Data_Free dec (10, 2),
[Data_Free (%)] dec (5, 2),
[++] char(2),
Log dec (10, 2),
Log_Used dec (10, 2),
[Log_Used (%)] dec (5, 2),
Log_Free dec (10, 2),
[Log_Free (%)] dec (5, 2) );
INSERT INTO #Tbl_Final
SELECT x.DatabaseName,
x.Data + y.Log AS 'TOTAL',
'=' AS '=',
x.Data_Used + y.Log_Used AS 'U',
(x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',
'+' AS '+',
x.Data_Free + y.Log_Free AS 'F',
(x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',
'==' AS '==',
x.Data,
x.Data_Used,
x.Data_Used*100/x.Data AS 'D_U(%)',
x.Data_Free,
x.Data_Free*100/x.Data AS 'D_F(%)',
'++' AS '++',
y.Log,
y.Log_Used,
y.Log_Used*100/y.Log AS 'L_U(%)',
y.Log_Free,
y.Log_Free*100/y.Log AS 'L_F(%)'
FROM
( SELECT d.DatabaseName,
SUM(d.T) AS 'Data',
SUM(d.U) AS 'Data_Used',
SUM(d.F) AS 'Data_Free'
FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY d.DatabaseName ) AS x
JOIN
( SELECT l.DatabaseName,
SUM(l.T) AS 'Log',
SUM(l.U) AS 'Log_Used',
SUM(l.F) AS 'Log_Free'
FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY l.DatabaseName ) AS y
ON x.DatabaseName = y.DatabaseName;
IF #Unit = 'KB'
UPDATE #Tbl_Final SET TOTAL = TOTAL * 1024,
used = used * 1024,
free = free * 1024,
Data = Data * 1024,
Data_Used = Data_Used * 1024,
Data_Free = Data_Free * 1024,
Log = Log * 1024,
Log_Used = Log_Used * 1024,
Log_Free = Log_Free * 1024;
IF #Unit = 'GB'
UPDATE #Tbl_Final SET TOTAL = TOTAL / 1024,
used = used / 1024,
free = free / 1024,
Data = Data / 1024,
Data_Used = Data_Used / 1024,
Data_Free = Data_Free / 1024,
Log = Log / 1024,
Log_Used = Log_Used / 1024,
Log_Free = Log_Free / 1024;
DECLARE #GrantTotal dec(11, 2);
SELECT #GrantTotal = SUM(TOTAL) FROM #Tbl_Final;
SELECT
CONVERT(dec(10, 2), TOTAL*100.0/#GrantTotal) AS 'WEIGHT (%)',
DatabaseName AS 'DATABASE',
CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)' AS 'USED (%)',
[+],
CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)' AS 'FREE (%)',
[=],
TOTAL,
[=],
CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', ' +
CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',
[+],
CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' +
CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'
FROM #Tbl_Final
WHERE DatabaseName LIKE ISNULL(#TargetDatabase, '%')
ORDER BY DatabaseName ASC;
IF #TargetDatabase IS NULL
SELECT CASE WHEN #Unit = 'GB' THEN 'GB' WHEN #Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',
SUM (used) AS 'USED',
SUM (free) AS 'FREE',
SUM (TOTAL) AS 'TOTAL',
SUM (Data) AS 'DATA',
SUM (Log) AS 'LOG'
FROM #Tbl_Final;
END
RETURN (0)
GO
I know this might sound a little arcanine but why not just stat the directory that contains the database.
if you use SQL Server Management Studio (from SQL 2005 or newer) you can just right-click properties on the database itself, and then click on the storage tab.
Related
I'm building a layer over an application that needs to catch the changes happens to the data and update another system with these changes (SIF) and I faced a problem with a specific table, the application truncates the table, and insert a new set of records every time the data reconciled.
In order to solve this problem, I used a shadow table and Merged the records from the original table, and as I found that I might use the same method with other tables in the future, I created a generic SP that reads the structure of the tow tables and constructs a merge statement then runs it and I'm sharing the SP in the first answer, hope someone makes use of it, any comment or question is welcomed.
The SP works as long as the two tables are identical and the change tracking is working beautifully.
1- Creating the SP
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [Compare2Tables](
#DestSchema as NVarchar(255) ,
#DestTable as NVarchar(255),
#SrcSchema as NVARCHAR(255) ,
#srcTable as NVARCHAR(255) ,
#AdditionalCondition as NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #JoiningFields as NVARCHAR(MAX)
DECLARE #MismatchingCondition as NVARCHAR(MAX)
DECLARE #UpdateOtherFields as NVARCHAR(MAX)
DECLARE #InsertDestFields as NVARCHAR(MAX)
DECLARE #InsertSrcFilds as NVARCHAR(MAX)
DECLARE #TheSQL as NVARCHAR(MAX)
DECLARE #CurrentColumn as NVARCHAR(255)
DECLARE #CurrentConstraint as NVARCHAR(255)
DECLARE #tablespecs TABLE (
TABLE_SCHEMA nvarchar(255) ,
TABLE_NAME nvarchar(255) ,
COLUMN_NAME nvarchar(255) ,
CONSTRAINT_NAME nvarchar(255)
)
insert into #tablespecs SELECT DISTINCT T.TABLE_SCHEMA , T.TABLE_NAME , T.COLUMN_NAME ,CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.COLUMNS t
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K ON T.TABLE_NAME = K.TABLE_NAME AND T.TABLE_SCHEMA = K.TABLE_SCHEMA AND T.COLUMN_NAME = K.COLUMN_NAME
WHERE T.TABLE_NAME = #DestTable
AND T.TABLE_SCHEMA = #DestSchema
set #JoiningFields = ' '
set #MismatchingCondition = ' '
set #UpdateOtherFields = ' '
set #InsertDestFields = ' '
set #InsertSrcFilds = ' '
while exists (select * from #tablespecs)
Begin
set #CurrentColumn = (Select top 1 Column_name from #tablespecs)
--select #CurrentColumn
Set #CurrentConstraint = (Select CONSTRAINT_NAME FROM #tablespecs WHERE COLUMN_NAME = #CurrentColumn)
if not #CurrentConstraint is null
set #JoiningFields = #JoiningFields + ' D.' + #CurrentColumn + '=S.' + #CurrentColumn + ' AND '
ELSE
begin
SET #MismatchingCondition = #MismatchingCondition + ' ISNULL(D.' + #CurrentColumn + ',0) <> ISNULL(S.' + #CurrentColumn + ',0) OR '
SET #updateOtherFields = #updateOtherFields + 'D.' +#CurrentColumn + ' = S.' + #CurrentColumn + ','
end
set #InsertDestFields = #InsertDestFields + #CurrentColumn + ','
set #InsertSrcFilds = #InsertSrcFilds + 'S.' + #CurrentColumn + ',';
delete from #tablespecs where Column_Name = #CurrentColumn
End
SET #JoiningFields = SUBSTRING(#JoiningFields , 1 , len(#JoiningFields) - 4)
SET #MismatchingCondition = SUBSTRING(#MismatchingCondition , 1 , len(#MismatchingCondition) - 3)
SET #UpdateOtherFields = SUBSTRING(#UpdateOtherFields , 1 , len(#updateOtherFields) - 1)
SET #InsertDestFields = SUBSTRING(#InsertDestFields , 1 , len(#InsertDestFields) - 1)
SET #InsertSrcFilds = SUBSTRING(#InsertSrcFilds , 1 , len(#InsertSrcFilds) - 1)
--select #JoiningFields JoiningFields , #UpdateOtherFields UpdateOtherFields , #MismatchingCondition MismatchingCondition , #InsertDestFields InsertDestFields , #InsertSrcFilds InsertSrcFilds
set #TheSQL = 'MERGE INTO ' + #DestSchema + '.' + #DestTable + ' AS D using (SELECT * FROM ' + #SrcSchema+'.'+ #SrcTable + ' ' + #AdditionalCondition + ') AS S ON ' + #JoiningFields + ' WHEN MATCHED AND (' + #MismatchingCondition + ')
THEN UPDATE SET ' + #updateOtherFields + '
WHEN NOT MATCHED BY TARGET THEN
INSERT (' + #InsertDestFields + ')
VALUES (' + #InsertSrcFilds + ')
WHEN NOT MATCHED BY SOURCE THEN
DELETE;'
EXECUTE sp_executesql #TheSQL
END
2- Now see the implementation
--Create theSource table
CREATE TABLE TheSource
(
TheID INT PRIMARY KEY,
TheName VARCHAR(100),
TheCost MONEY,
ProductionYear VARCHAR(4)
)
GO
--Fill some records in TheSource
INSERT INTO TheSource
VALUES
(1, 'Word', 10.00,'2018'),
(2, 'Access', 20.00,'2018'),
(3, 'Excel', 30.00,'2017'),
(4, 'PowerPoint', 40.00,'2017')
GO
--Create Destination table
CREATE TABLE TheDest
(
TheID INT PRIMARY KEY,
TheName VARCHAR(100),
TheCost MONEY,
ProductionYear VARCHAR(4)
)
GO
--The Dest table is left with no records on purpose
SELECT * FROM TheSource
SELECT * FROM TheDest
GO
--The folloing syntax will fill only products of 2017
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource','Where ProductionYear = 2017'
SELECT * FROM TheDest
-- Syncronizing all records regardless of the year
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource',' '
SELECT * FROM TheDest
--Updating one row in the source, then sync
update TheSource set TheCost = 33.00 where TheName = 'Access'
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource',' '
SELECT * FROM TheDest
-- updating all records in the source, then sync
update TheSource set TheCost = TheCost * 0.75
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource',' '
SELECT * FROM TheDest
When using "Generate Script" feature in MS SQL Management Studio we get data exported as well, but all values are inserted in a separate steps, which looks something like
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted]) VALUES (3, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 30 %', NULL, 13, 0)
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted]) VALUES (4, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 40 %', NULL, 14, 0)
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted]) VALUES (5, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 50 %', NULL, 15, 0)
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted]) VALUES (6, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 60 %', NULL, 16, 0)
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted]) VALUES (7, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 70 %', NULL, 17, 0)
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted]) VALUES (8, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 80 %', NULL, 18, 0)
Is there any way to make this script generation and forcing SSMS to create insert queries in a single or several larger steps, like:
INSERT [dbo].[table] ([table_id], [table_version], [table_timestamp], [table_user], [table_percent], [table_hid], [table_latestversionid], [table_isdeleted])
VALUES
(3, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 30 %', NULL, 13, 0),
(4, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 40 %', NULL, 14, 0),
(5, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 50 %', NULL, 15, 0),
(6, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 60 %', NULL, 16, 0),
(7, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 70 %', NULL, 17, 0),
(8, -1, CAST(N'2015-06-04 13:03:38.000' AS DateTime), N'init', N' 80 %', NULL, 18, 0);
Thanks
--First Create The SP GenerateInsert The Run The Below Mention CODE Which will give the Desire Output..
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.GenerateInsert') AND type in (N'P', N'PC'))
DROP PROCEDURE dbo.GenerateInsert;
GO
CREATE PROCEDURE dbo.GenerateInsert
(
#ObjectName nvarchar(261)
, #TargetObjectName nvarchar(261) = NULL
, #OmmitInsertColumnList bit = 0
, #GenerateSingleInsertPerRow bit = 0
, #UseSelectSyntax bit = 0
, #UseColumnAliasInSelect bit = 0
, #FormatCode bit = 1
, #GenerateOneColumnPerLine bit = 0
, #GenerateGo bit = 0
, #PrintGeneratedCode bit = 1
, #TopExpression nvarchar(max) = NULL
, #FunctionParameters nvarchar(max) = NULL
, #SearchCondition nvarchar(max) = NULL
, #OrderByExpression nvarchar(max) = NULL
, #OmmitUnsupportedDataTypes bit = 1
, #PopulateIdentityColumn bit = 0
, #PopulateTimestampColumn bit = 0
, #PopulateComputedColumn bit = 0
, #GenerateProjectInfo bit = 1
, #GenerateSetNoCount bit = 1
, #GenerateStatementTerminator bit = 1
, #ShowWarnings bit = 1
, #Debug bit = 0
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CrLf char(2)
SET #CrLf = CHAR(13) + CHAR(10);
DECLARE #ColumnName sysname;
DECLARE #DataType sysname;
DECLARE #ColumnList nvarchar(max);
SET #ColumnList = N'';
DECLARE #SelectList nvarchar(max);
SET #SelectList = N'';
DECLARE #SelectStatement nvarchar(max);
SET #SelectStatement = N'';
DECLARE #OmittedColumnList nvarchar(max);
SET #OmittedColumnList = N'';
DECLARE #InsertSql nvarchar(max);
SET #InsertSql = N'INSERT INTO ' + COALESCE(#TargetObjectName,#ObjectName);
DECLARE #ValuesSql nvarchar(max);
SET #ValuesSql = N'VALUES (';
DECLARE #SelectSql nvarchar(max);
SET #SelectSql = N'SELECT ';
DECLARE #TableData table (TableRow nvarchar(max));
DECLARE #Results table (TableRow nvarchar(max));
DECLARE #TableRow nvarchar(max);
DECLARE #RowNo int;
IF PARSENAME(#ObjectName,3) IS NOT NULL
OR PARSENAME(#ObjectName,4) IS NOT NULL
BEGIN
RAISERROR(N'Server and database names are not allowed to specify in #ObjectName parameter. Required format is [schema_name.]object_name',16,1);
RETURN -1;
END
IF OBJECT_ID(#ObjectName,N'U') IS NULL -- USER_TABLE
AND OBJECT_ID(#ObjectName,N'V') IS NULL -- VIEW
AND OBJECT_ID(#ObjectName,N'IF') IS NULL -- SQL_INLINE_TABLE_VALUED_FUNCTION
AND OBJECT_ID(#ObjectName,N'TF') IS NULL -- SQL_TABLE_VALUED_FUNCTION
BEGIN
RAISERROR(N'User table, view, table-valued or inline function %s not found or insuficient permission to query the provided object.',16,1,#ObjectName);
RETURN -1;
END
IF NOT EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE IN ('BASE TABLE','VIEW')
AND TABLE_NAME = PARSENAME(#ObjectName,1)
AND (TABLE_SCHEMA = PARSENAME(#ObjectName,2)
OR PARSENAME(#ObjectName,2) IS NULL)
) AND NOT EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE IN ('FUNCTION')
AND DATA_TYPE = 'TABLE'
AND SPECIFIC_NAME = PARSENAME(#ObjectName,1)
AND (SPECIFIC_SCHEMA = PARSENAME(#ObjectName,2)
OR PARSENAME(#ObjectName,2) IS NULL)
)
BEGIN
RAISERROR(N'User table, view, table-valued or inline function %s not found or insuficient permission to query the provided object.',16,1,#ObjectName);
RETURN -1;
END
DECLARE ColumnCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT c.name ColumnName
,COALESCE(TYPE_NAME(c.system_type_id),t.name) DataType
FROM sys.objects o
INNER JOIN sys.columns c ON c.object_id = o.object_id
LEFT JOIN sys.types t ON t.system_type_id = c.system_type_id
AND t.user_type_id = c.user_type_id
WHERE o.type IN (N'U',N'V',N'IF',N'TF')
-- U = USER_TABLE
-- V = VIEW
-- IF = SQL_INLINE_TABLE_VALUED_FUNCTION
-- TF = SQL_TABLE_VALUED_FUNCTION
AND (o.object_id = OBJECT_ID(#ObjectName)
OR o.name = #ObjectName)
AND (COLUMNPROPERTY(c.object_id,c.name,'IsIdentity') != 1
OR #PopulateIdentityColumn = 1)
AND (COLUMNPROPERTY(c.object_id,c.name,'IsComputed') != 1
OR #PopulateComputedColumn = 1)
ORDER BY COLUMNPROPERTY(c.object_id,c.name,'ordinal') -- ORDINAL_POSITION
FOR READ ONLY
;
OPEN ColumnCursor;
FETCH NEXT FROM ColumnCursor INTO #ColumnName,#DataType;
WHILE ##FETCH_STATUS = 0
BEGIN
-- Handle different data types
DECLARE #ColumnExpression nvarchar(max);
SET #ColumnExpression =
CASE
WHEN #DataType IN ('char','varchar','text','uniqueidentifier')
THEN N'ISNULL(''''''''+REPLACE(CONVERT(varchar(max),'+ QUOTENAME(#ColumnName) + N'),'''''''','''''''''''')+'''''''',''NULL'') COLLATE database_default'
WHEN #DataType IN ('nchar','nvarchar','sysname','ntext','sql_variant','xml')
THEN N'ISNULL(''N''''''+REPLACE(CONVERT(nvarchar(max),'+ QUOTENAME(#ColumnName) + N'),'''''''','''''''''''')+'''''''',''NULL'') COLLATE database_default'
WHEN #DataType IN ('int','bigint','smallint','tinyint','decimal','numeric','bit')
THEN N'ISNULL(CONVERT(varchar(max),'+ QUOTENAME(#ColumnName) + N'),''NULL'') COLLATE database_default'
WHEN #DataType IN ('float','real','money','smallmoney')
THEN N'ISNULL(CONVERT(varchar(max),'+ QUOTENAME(#ColumnName) + N',2),''NULL'') COLLATE database_default'
WHEN #DataType IN ('datetime','smalldatetime','date','time','datetime2','datetimeoffset')
THEN N'''CONVERT('+#DataType+',''+ISNULL(''''''''+CONVERT(varchar(max),'+ QUOTENAME(#ColumnName) + N',121)+'''''''',''NULL'') COLLATE database_default' + '+'',121)'''
WHEN #DataType IN ('rowversion','timestamp')
THEN
CASE WHEN #PopulateTimestampColumn = 1
THEN N'''CONVERT(varbinary(max),''+ISNULL(''''''''+CONVERT(varchar(max),CONVERT(varbinary(max),'+ QUOTENAME(#ColumnName) + N'),1)+'''''''',''NULL'') COLLATE database_default' + '+'',1)'''
ELSE N'''NULL''' END
WHEN #DataType IN ('binary','varbinary','image')
THEN N'''CONVERT(varbinary(max),''+ISNULL(''''''''+CONVERT(varchar(max),CONVERT(varbinary(max),'+ QUOTENAME(#ColumnName) + N'),1)+'''''''',''NULL'') COLLATE database_default' + '+'',1)'''
WHEN #DataType IN ('geography')
-- convert geography to text: ?? column.STAsText();
-- convert text to geography: ?? geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326);
THEN NULL
ELSE NULL END;
IF #ColumnExpression IS NULL
AND #OmmitUnsupportedDataTypes != 1
BEGIN
RAISERROR(N'Datatype %s is not supported. Use #OmmitUnsupportedDataTypes to exclude unsupported columns.',16,1,#DataType);
RETURN -1;
END
IF #ColumnExpression IS NULL
BEGIN
SET #OmittedColumnList = #OmittedColumnList
+ CASE WHEN #OmittedColumnList != N'' THEN N'; ' ELSE N'' END
+ N'column ' + QUOTENAME(#ColumnName)
+ N', datatype ' + #DataType;
END
IF #ColumnExpression IS NOT NULL
BEGIN
SET #ColumnList = #ColumnList
+ CASE WHEN #ColumnList != N'' THEN N',' ELSE N'' END
+ QUOTENAME(#ColumnName)
+ CASE WHEN #GenerateOneColumnPerLine = 1 THEN #CrLf ELSE N'' END;
SET #SelectList = #SelectList
+ CASE WHEN #SelectList != N'' THEN N'+'',''+' + #CrLf ELSE N'' END
+ #ColumnExpression
+ CASE WHEN #UseColumnAliasInSelect = 1 AND #UseSelectSyntax = 1 THEN N'+'' ' + QUOTENAME(#ColumnName) + N'''' ELSE N'' END
+ CASE WHEN #GenerateOneColumnPerLine = 1 THEN N'+CHAR(13)+CHAR(10)' ELSE N'' END;
END
FETCH NEXT FROM ColumnCursor INTO #ColumnName,#DataType;
END
CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;
IF NULLIF(#ColumnList,N'') IS NULL
BEGIN
RAISERROR(N'No columns to select.',16,1);
RETURN -1;
END
IF #Debug = 1
BEGIN
PRINT(N'--Column list');
PRINT(#ColumnList);
END
IF NULLIF(#OmittedColumnList,'') IS NOT NULL
AND #ShowWarnings = 1
BEGIN
PRINT(N'--*************************');
PRINT(N'--WARNING: The following columns have been omitted because of unsupported datatypes: ' + #OmittedColumnList);
PRINT(N'--*************************');
END
IF #GenerateSingleInsertPerRow = 1
BEGIN
SET #SelectList =
N'''' + #InsertSql + N'''+' + #CrLf
+ CASE WHEN #FormatCode = 1
THEN N'CHAR(13)+CHAR(10)+' + #CrLf
ELSE N''' ''+'
END
+ CASE WHEN #OmmitInsertColumnList = 1
THEN N''
ELSE N'''(' + #ColumnList + N')''+' + #CrLf
END
+ CASE WHEN #FormatCode = 1
THEN N'CHAR(13)+CHAR(10)+' + #CrLf
ELSE N''' ''+'
END
+ CASE WHEN #UseSelectSyntax = 1
THEN N'''' + #SelectSql + N'''+'
ELSE N'''' + #ValuesSql + N'''+'
END
+ #CrLf
+ #SelectList
+ CASE WHEN #UseSelectSyntax = 1
THEN N''
ELSE N'+' + #CrLf + N''')'''
END
+ CASE WHEN #GenerateStatementTerminator = 1
THEN N'+'';'''
ELSE N''
END
+ CASE WHEN #GenerateGo = 1
THEN N'+' + #CrLf + N'CHAR(13)+CHAR(10)+' + #CrLf + N'''GO'''
ELSE N''
END
;
END ELSE BEGIN
SET #SelectList =
CASE WHEN #UseSelectSyntax = 1
THEN N'''' + #SelectSql + N'''+'
ELSE N'''(''+'
END
+ #CrLf
+ #SelectList
+ CASE WHEN #UseSelectSyntax = 1
THEN N''
ELSE N'+' + #CrLf + N''')'''
END
;
END
SET #SelectStatement = N'SELECT'
+ CASE WHEN NULLIF(#TopExpression,N'') IS NOT NULL
THEN N' TOP ' + #TopExpression
ELSE N'' END
+ #CrLf + #SelectList + #CrLf
+ N'FROM ' + #ObjectName
+ CASE WHEN NULLIF(#FunctionParameters,N'') IS NOT NULL
THEN #FunctionParameters
ELSE N'' END
+ CASE WHEN NULLIF(#SearchCondition,N'') IS NOT NULL
THEN #CrLf + N'WHERE ' + #SearchCondition
ELSE N'' END
+ CASE WHEN NULLIF(#OrderByExpression,N'') IS NOT NULL
THEN #CrLf + N'ORDER BY ' + #OrderByExpression
ELSE N'' END
+ #CrLf + N';' + #CrLf + #CrLf
;
IF #Debug = 1
BEGIN
PRINT(#CrLf + N'--Select statement');
PRINT(#SelectStatement);
END
INSERT INTO #TableData
EXECUTE (#SelectStatement);
IF #GenerateProjectInfo = 1
BEGIN
INSERT INTO #Results
SELECT N'--INSERTs generated by GenerateInsert (Build 6)'
UNION SELECT N''
END
IF #GenerateSetNoCount = 1
BEGIN
INSERT INTO #Results
SELECT N'SET NOCOUNT ON'
END
IF #PopulateIdentityColumn = 1
BEGIN
INSERT INTO #Results
SELECT N'SET IDENTITY_INSERT ' + COALESCE(#TargetObjectName,#ObjectName) + N' ON'
END
IF #GenerateSingleInsertPerRow = 1
BEGIN
INSERT INTO #Results
SELECT TableRow
FROM #TableData
END ELSE BEGIN
IF #FormatCode = 1
BEGIN
INSERT INTO #Results
SELECT #InsertSql;
IF #OmmitInsertColumnList != 1
BEGIN
INSERT INTO #Results
SELECT N'(' + #ColumnList + N')';
END
IF #UseSelectSyntax != 1
BEGIN
INSERT INTO #Results
SELECT N'VALUES';
END
END ELSE BEGIN
INSERT INTO #Results
SELECT #InsertSql
+ CASE WHEN #OmmitInsertColumnList = 1 THEN N'' ELSE N' (' + #ColumnList + N')' END
+ CASE WHEN #UseSelectSyntax = 1 THEN N'' ELSE N' VALUES' END
END
SET #RowNo = 0;
DECLARE DataCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT TableRow
FROM #TableData
FOR READ ONLY
;
OPEN DataCursor;
FETCH NEXT FROM DataCursor INTO #TableRow;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #RowNo = #RowNo + 1;
INSERT INTO #Results
SELECT
CASE WHEN #UseSelectSyntax = 1
THEN CASE WHEN #RowNo > 1 THEN N'UNION' + CASE WHEN #FormatCode = 1 THEN #CrLf ELSE N' ' END ELSE N'' END
ELSE CASE WHEN #RowNo > 1 THEN N',' ELSE N' ' END END
+ #TableRow;
FETCH NEXT FROM DataCursor INTO #TableRow;
END
CLOSE DataCursor;
DEALLOCATE DataCursor;
IF #GenerateStatementTerminator = 1
BEGIN
INSERT INTO #Results
SELECT N';';
END
IF #GenerateGo = 1
BEGIN
INSERT INTO #Results
SELECT N'GO';
END
END
IF #PopulateIdentityColumn = 1
BEGIN
INSERT INTO #Results
SELECT N'SET IDENTITY_INSERT ' + COALESCE(#TargetObjectName,#ObjectName) + N' OFF'
END
IF #FormatCode = 1
BEGIN
INSERT INTO #Results
SELECT N''; -- An empty line at the end
END
IF #PrintGeneratedCode = 1
BEGIN
DECLARE #LongRows bigint;
SET #LongRows = (SELECT COUNT(*) FROM #Results WHERE LEN(TableRow) > 4000);
IF #LongRows > 0
AND #ShowWarnings = 1
BEGIN
PRINT(N'--*************************');
IF #LongRows = 1
PRINT(N'--WARNING: ' + CONVERT(nvarchar(max), #LongRows) + N' Row is very long and will be chopped at every 4000 character.')
ELSE
PRINT(N'--WARNING: ' + CONVERT(nvarchar(max), #LongRows) + N' Rows are very long and will be chopped at every 4000 character.');
PRINT(N'-- If this is an issue then the workaround is to use #PrintGeneratedCode = 0 and output "Result to Grid" in SSMS.');
PRINT(N'--*************************');
END
DECLARE ResultsCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT TableRow
FROM #Results
FOR READ ONLY
;
OPEN ResultsCursor;
FETCH NEXT FROM ResultsCursor INTO #TableRow;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #CurrentEnd bigint; -- track the length of the next sub-string
DECLARE #Offset tinyint; -- tracks the amount of offset needed
SET #TableRow = REPLACE(REPLACE(#TableRow, CHAR(13) + CHAR(10), CHAR(10)), CHAR(13), CHAR(10));
WHILE LEN(#TableRow) > 1
BEGIN
IF CHARINDEX(CHAR(10), #TableRow) BETWEEN 1 AND 4000
BEGIN
SET #CurrentEnd = CHARINDEX(CHAR(10), #TableRow) - 1;
SET #Offset = 2;
END
ELSE
BEGIN
SET #CurrentEnd = 4000;
SET #Offset = 1;
END
PRINT(SUBSTRING(#TableRow, 1, #CurrentEnd));
SET #TableRow = SUBSTRING(#TableRow, #CurrentEnd + #Offset, LEN(#TableRow))
END
FETCH NEXT FROM ResultsCursor INTO #TableRow;
END
CLOSE ResultsCursor;
DEALLOCATE ResultsCursor;
END ELSE BEGIN
SELECT *
FROM #Results;
END
END
GO
----==============================
--ONCE SP Created run The following Code With Table_Name..
DECLARE #Name NVARCHAR(261)='Table_Name';
DECLARE TableCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT QUOTENAME(s.name) + '.' + QUOTENAME(t.name) ObjectName
FROM sys.tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.name NOT LIKE 'sys%' AND t.name='Table_Name'
FOR READ ONLY
;
OPEN TableCursor;
FETCH NEXT FROM TableCursor INTO #Name;
WHILE ##FETCH_STATUS = 0
BEGIN
EXECUTE dbo.GenerateInsert #ObjectName = #Name;
FETCH NEXT FROM TableCursor INTO #Name;
END
CLOSE TableCursor;
DEALLOCATE TableCursor;
what were the last few queries ran on SQL Server and with client name (system name) ?
i am running this query in server side
below query getting queries
SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC
how can i get system name
for e.g
time | query | System Name
You could check the sp_who and sp_who2 text.
create procedure sys.sp_who2 --- 1995/11/03 10:16
#loginame sysname = NULL
as
set nocount on
declare
#retcode int
declare
#sidlow varbinary(85)
,#sidhigh varbinary(85)
,#sid1 varbinary(85)
,#spidlow int
,#spidhigh int
declare
#charMaxLenLoginName varchar(6)
,#charMaxLenDBName varchar(6)
,#charMaxLenCPUTime varchar(10)
,#charMaxLenDiskIO varchar(10)
,#charMaxLenHostName varchar(10)
,#charMaxLenProgramName varchar(10)
,#charMaxLenLastBatch varchar(10)
,#charMaxLenCommand varchar(10)
declare
#charsidlow varchar(85)
,#charsidhigh varchar(85)
,#charspidlow varchar(11)
,#charspidhigh varchar(11)
-- defaults
select #retcode = 0 -- 0=good ,1=bad.
select #sidlow = convert(varbinary(85), (replicate(char(0), 85)))
select #sidhigh = convert(varbinary(85), (replicate(char(1), 85)))
select
#spidlow = 0
,#spidhigh = 32767
--------------------------------------------------------------
IF (#loginame IS NULL) --Simple default to all LoginNames.
GOTO LABEL_17PARM1EDITED
-- select #sid1 = suser_sid(#loginame)
select #sid1 = null
if exists(select * from sys.syslogins where loginname = #loginame)
select #sid1 = sid from sys.syslogins where loginname = #loginame
IF (#sid1 IS NOT NULL) --Parm is a recognized login name.
begin
select #sidlow = suser_sid(#loginame)
,#sidhigh = suser_sid(#loginame)
GOTO LABEL_17PARM1EDITED
end
--------
IF (lower(#loginame collate Latin1_General_CI_AS) IN ('active')) --Special action, not sleeping.
begin
select #loginame = lower(#loginame collate Latin1_General_CI_AS)
GOTO LABEL_17PARM1EDITED
end
--------
IF (patindex ('%[^0-9]%' , isnull(#loginame,'z')) = 0) --Is a number.
begin
select
#spidlow = convert(int, #loginame)
,#spidhigh = convert(int, #loginame)
GOTO LABEL_17PARM1EDITED
end
--------
raiserror(15007,-1,-1,#loginame)
select #retcode = 1
GOTO LABEL_86RETURN
LABEL_17PARM1EDITED:
-------------------- Capture consistent sysprocesses. -------------------
select
spid
,status
,sid
,hostname
,program_name
,cmd
,cpu
,physical_io
,blocked
,dbid
,convert(sysname, rtrim(loginame))
as loginname
,spid as 'spid_sort'
, substring( convert(varchar,last_batch,111) ,6 ,5 ) + ' '
+ substring( convert(varchar,last_batch,113) ,13 ,8 )
as 'last_batch_char'
,request_id
into #tb1_sysprocesses
from sys.sysprocesses_ex with (nolock)
if ##error <> 0
begin
select #retcode = ##error
GOTO LABEL_86RETURN
end
--------Screen out any rows?
if (#loginame in ('active'))
delete #tb1_sysprocesses
where lower(status) = 'sleeping'
and upper(cmd) in (
'AWAITING COMMAND'
,'LAZY WRITER'
,'CHECKPOINT SLEEP'
)
and blocked = 0
--------Prepare to dynamically optimize column widths.
select
#charsidlow = convert(varchar(85),#sidlow)
,#charsidhigh = convert(varchar(85),#sidhigh)
,#charspidlow = convert(varchar,#spidlow)
,#charspidhigh = convert(varchar,#spidhigh)
select
#charMaxLenLoginName =
convert( varchar
,isnull( max( datalength(loginname)) ,5)
)
,#charMaxLenDBName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),db_name(dbid))))) ,6)
)
,#charMaxLenCPUTime =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cpu)))) ,7)
)
,#charMaxLenDiskIO =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),physical_io)))) ,6)
)
,#charMaxLenCommand =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cmd)))) ,7)
)
,#charMaxLenHostName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),hostname)))) ,8)
)
,#charMaxLenProgramName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),program_name)))) ,11)
)
,#charMaxLenLastBatch =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),last_batch_char)))) ,9)
)
from
#tb1_sysprocesses
where
spid >= #spidlow
and spid <= #spidhigh
--------Output the report.
EXEC(
'
SET nocount off
SELECT
SPID = convert(char(5),spid)
,Status =
CASE lower(status)
When ''sleeping'' Then lower(status)
Else upper(status)
END
,Login = substring(loginname,1,' + #charMaxLenLoginName + ')
,HostName =
CASE hostname
When Null Then '' .''
When '' '' Then '' .''
Else substring(hostname,1,' + #charMaxLenHostName + ')
END
,BlkBy =
CASE isnull(convert(char(5),blocked),''0'')
When ''0'' Then '' .''
Else isnull(convert(char(5),blocked),''0'')
END
,DBName = substring(case when dbid = 0 then null when dbid <> 0 then db_name(dbid) end,1,' + #charMaxLenDBName + ')
,Command = substring(cmd,1,' + #charMaxLenCommand + ')
,CPUTime = substring(convert(varchar,cpu),1,' + #charMaxLenCPUTime + ')
,DiskIO = substring(convert(varchar,physical_io),1,' + #charMaxLenDiskIO + ')
,LastBatch = substring(last_batch_char,1,' + #charMaxLenLastBatch + ')
,ProgramName = substring(program_name,1,' + #charMaxLenProgramName + ')
,SPID = convert(char(5),spid) --Handy extra for right-scrolling users.
,REQUESTID = convert(char(5),request_id)
from
#tb1_sysprocesses --Usually DB qualification is needed in exec().
where
spid >= ' + #charspidlow + '
and spid <= ' + #charspidhigh + '
-- (Seems always auto sorted.) order by spid_sort
SET nocount on
'
)
LABEL_86RETURN:
if (object_id('tempdb..#tb1_sysprocesses') is not null)
drop table #tb1_sysprocesses
return #retcode -- sp_who2
Hope this helps.
The below query should help you:
SELECT conn.session_id, sson.host_name, sson.login_name,
sqltxt.text, sson.login_time, sson.status
FROM sys.dm_exec_connections conn
INNER JOIN sys.dm_exec_sessions sson
ON conn.session_id = sson.session_id
CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS sqltxt
ORDER BY conn.session_id desc
Source: http://www.sqlservercurry.com/2011/12/last-run-query-in-sql-server.html
I have a certain dilemma, using SQL server 2005 and 2008.
There's an emergency that needs to be performed, and the only way (SLA-bound) to do so is to use a certain SQL login. The problem is, the person who has the password can't be reached, and we soon need to perform the update (through an application and using scripts and ssis).
The current discussion is to change the password and then revert back to the original.
So, is this possible? To export or backup the SQL login? (Coz if so, then we can indeed easily change the password, perform the update, then restore the original one)
For this scenario, kindly assume that we need to backup the
SQL login's info (including the password)
You can script out the login with a password hash. Then do what you need to do and finally drop the login and recreate it using the script. There are several articles out there describing how to do the scripting step, e.g.: http://weblogs.sqlteam.com/billg/archive/2010/07/08/Scripting-out-SQL-Server-Logins.aspx
However, dropping the login drops all permissions that where granted to that login. Also, there are a few things that prevent a login from being dropped, e.g. it owning a database.
So you also need to script out the permissions and temporarily reassign ownership of those logins.
It is possible that you can use the password hash to directly reset the password, but I have never tried that. If that works you would not have to do all the dropping and recreating.
Script for backing up all logins:
USE [master]
GO
/****** Object: UserDefinedFunction [dbo].[fn_hexadecimal] ****/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_hexadecimal]
(
-- Add the parameters for the function here
#binvalue varbinary(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE #charvalue varchar(256)
DECLARE #i int
DECLARE #length int
DECLARE #hexstring char(16)
SELECT #charvalue = '0x'
SELECT #i = 1
SELECT #length = DATALENGTH (#binvalue)
SELECT #hexstring = '0123456789ABCDEF'
WHILE (#i <= #length)
BEGIN
DECLARE #tempint int
DECLARE #firstint int
DECLARE #secondint int
SELECT #tempint = CONVERT(int, SUBSTRING(#binvalue,#i,1))
SELECT #firstint = FLOOR(#tempint/16)
SELECT #secondint = #tempint - (#firstint*16)
SELECT #charvalue = #charvalue +
SUBSTRING(#hexstring, #firstint+1, 1) +
SUBSTRING(#hexstring, #secondint+1, 1)
SELECT #i = #i + 1
END
return #charvalue
END
GO
SET NOCOUNT ON
GO
--use MASTER
GO
PRINT '-----------------------------------------------------------------------------'
PRINT '-- Script created on ' + CAST(GETDATE() AS VARCHAR(100))
PRINT '-----------------------------------------------------------------------------'
PRINT ''
PRINT '-----------------------------------------------------------------------------'
PRINT '-- Create the windows logins'
PRINT '-----------------------------------------------------------------------------'
SELECT 'IF NOT EXISTS (SELECT * FROM master.sys.server_principals WHERE [name] = ''' + [name] + ''')
CREATE LOGIN [' + [name] + '] FROM WINDOWS WITH DEFAULT_DATABASE=[' +
default_database_name + '], DEFAULT_LANGUAGE=[us_english]
GO
'
FROM master.sys.server_principals
where type_desc In ('WINDOWS_GROUP', 'WINDOWS_LOGIN')
AND [name] not like 'BUILTIN%'
and [NAME] not like 'NT AUTHORITY%'
and [name] not like '%\SQLServer%'
GO
PRINT '-----------------------------------------------------------------------------'
PRINT '-- Create the SQL Logins'
PRINT '-----------------------------------------------------------------------------'
select 'IF NOT EXISTS (SELECT * FROM master.sys.sql_logins WHERE [name] = ''' + [name] + ''')
CREATE LOGIN [' + [name] + ']
WITH PASSWORD=' + [master].[dbo].[fn_hexadecimal](password_hash) + ' HASHED,
SID = ' + [master].[dbo].[fn_hexadecimal]([sid]) + ',
DEFAULT_DATABASE=[' + default_database_name + '], DEFAULT_LANGUAGE=[us_english],
CHECK_EXPIRATION=' + CASE WHEN is_expiration_checked = 1 THEN 'ON' ELSE 'OFF' END + ', CHECK_POLICY=OFF
GO
IF EXISTS (SELECT * FROM master.sys.sql_logins WHERE [name] = ''' + [name] + ''')
ALTER LOGIN [' + [name] + ']
WITH CHECK_EXPIRATION=' +
CASE WHEN is_expiration_checked = 1 THEN 'ON' ELSE 'OFF' END + ', CHECK_POLICY=' +
CASE WHEN is_policy_checked = 1 THEN 'ON' ELSE 'OFF' END + '
GO
'
--[name], [sid] , password_hash
from master.sys.sql_logins
where type_desc = 'SQL_LOGIN'
and [name] not in ('sa', 'guest')
PRINT '-----------------------------------------------------------------------------'
PRINT '-- Disable any logins'
PRINT '-----------------------------------------------------------------------------'
SELECT 'ALTER LOGIN [' + [name] + '] DISABLE
GO
'
from master.sys.server_principals
where is_disabled = 1
PRINT '-----------------------------------------------------------------------------'
PRINT '-- Assign groups'
PRINT '-----------------------------------------------------------------------------'
select
'EXEC master..sp_addsrvrolemember #loginame = N''' + l.name + ''', #rolename = N''' + r.name + '''
GO
'
from master.sys.server_role_members rm
join master.sys.server_principals r on r.principal_id = rm.role_principal_id
join master.sys.server_principals l on l.principal_id = rm.member_principal_id
where l.[name] not in ('sa')
AND l.[name] not like 'BUILTIN%'
and l.[NAME] not like 'NT AUTHORITY%'
and l.[name] not like '%\SQLServer%'
You can use script to backup/restore login using microsoft sql server
Step 1: Create sp_help_revlogin procedure
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
#binvalue varbinary(256),
#hexvalue varchar (514) OUTPUT
AS
DECLARE #charvalue varchar (514)
DECLARE #i int
DECLARE #length int
DECLARE #hexstring char(16)
SELECT #charvalue = '0x'
SELECT #i = 1
SELECT #length = DATALENGTH (#binvalue)
SELECT #hexstring = '0123456789ABCDEF'
WHILE (#i <= #length)
BEGIN
DECLARE #tempint int
DECLARE #firstint int
DECLARE #secondint int
SELECT #tempint = CONVERT(int, SUBSTRING(#binvalue,#i,1))
SELECT #firstint = FLOOR(#tempint/16)
SELECT #secondint = #tempint - (#firstint*16)
SELECT #charvalue = #charvalue +
SUBSTRING(#hexstring, #firstint+1, 1) +
SUBSTRING(#hexstring, #secondint+1, 1)
SELECT #i = #i + 1
END
SELECT #hexvalue = #charvalue
GO
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin #login_name sysname = NULL AS
DECLARE #name sysname
DECLARE #type varchar (1)
DECLARE #hasaccess int
DECLARE #denylogin int
DECLARE #is_disabled int
DECLARE #PWD_varbinary varbinary (256)
DECLARE #PWD_string varchar (514)
DECLARE #SID_varbinary varbinary (85)
DECLARE #SID_string varchar (514)
DECLARE #tmpstr varchar (1024)
DECLARE #is_policy_checked varchar (3)
DECLARE #is_expiration_checked varchar (3)
DECLARE #defaultdb sysname
IF (#login_name IS NULL)
DECLARE login_curs CURSOR FOR
SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
DECLARE login_curs CURSOR FOR
SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM
sys.server_principals p LEFT JOIN sys.syslogins l
ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = #login_name
OPEN login_curs
FETCH NEXT FROM login_curs INTO #SID_varbinary, #name, #type, #is_disabled, #defaultdb, #hasaccess, #denylogin
IF (##fetch_status = -1)
BEGIN
PRINT 'No login(s) found.'
CLOSE login_curs
DEALLOCATE login_curs
RETURN -1
END
SET #tmpstr = '/* sp_help_revlogin script '
PRINT #tmpstr
SET #tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + ##SERVERNAME + ' */'
PRINT #tmpstr
PRINT ''
WHILE (##fetch_status <> -1)
BEGIN
IF (##fetch_status <> -2)
BEGIN
PRINT ''
SET #tmpstr = '-- Login: ' + #name
PRINT #tmpstr
IF (#type IN ( 'G', 'U'))
BEGIN -- NT authenticated account/group
SET #tmpstr = 'CREATE LOGIN ' + QUOTENAME( #name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + #defaultdb + ']'
END
ELSE BEGIN -- SQL Server authentication
-- obtain password and sid
SET #PWD_varbinary = CAST( LOGINPROPERTY( #name, 'PasswordHash' ) AS varbinary (256) )
EXEC sp_hexadecimal #PWD_varbinary, #PWD_string OUT
EXEC sp_hexadecimal #SID_varbinary,#SID_string OUT
-- obtain password policy state
SELECT #is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = #name
SELECT #is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = #name
SET #tmpstr = 'CREATE LOGIN ' + QUOTENAME( #name ) + ' WITH PASSWORD = ' + #PWD_string + ' HASHED, SID = ' + #SID_string + ', DEFAULT_DATABASE = [' + #defaultdb + ']'
IF ( #is_policy_checked IS NOT NULL )
BEGIN
SET #tmpstr = #tmpstr + ', CHECK_POLICY = ' + #is_policy_checked
END
IF ( #is_expiration_checked IS NOT NULL )
BEGIN
SET #tmpstr = #tmpstr + ', CHECK_EXPIRATION = ' + #is_expiration_checked
END
END
IF (#denylogin = 1)
BEGIN -- login is denied access
SET #tmpstr = #tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( #name )
END
ELSE IF (#hasaccess = 0)
BEGIN -- login exists but does not have access
SET #tmpstr = #tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( #name )
END
IF (#is_disabled = 1)
BEGIN -- login is disabled
SET #tmpstr = #tmpstr + '; ALTER LOGIN ' + QUOTENAME( #name ) + ' DISABLE'
END
PRINT #tmpstr
END
FETCH NEXT FROM login_curs INTO #SID_varbinary, #name, #type, #is_disabled, #defaultdb, #hasaccess, #denylogin
END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO
Step 2: Execute sp_help_revlogin and copy result to restore login
Reference http://giasutinhoc.vn
I am trying to create multiple triggers with only uploading one script into an Oracle DB / APEX workspace, and running it once.
Here is a brief script compared to the one im trying to use:
create or replace trigger "BI_TEC_ROLES"
before insert on "TEC_ROLES"
for each row
begin
if :NEW."ROLE_ID" is null then
select "TEC_ROLES_SEQ".nextval into :NEW."ROLE_ID" from dual;
end if;
end;
create or replace trigger "BI_TEC_STATUSES"
before insert on "TEC_STATUSES"
for each row
begin
if :NEW."STATUS_ID" is null then
select "TEC_STATUSES_SEQ".nextval into :NEW."STATUS_ID" from dual;
end if;
end;
create or replace trigger "BI_TEC_SUBS"
before insert on "TEC_SUBS"
for each row
begin
if :NEW."SUB_ID" is null then
select "TEC_SUBS_SEQ".nextval into :NEW."SUB_ID" from dual;
end if;
end;
I have tried putting GO in between each individual block, but still only creates the first trigger then gives me an error for the second saying:
Error(7,1): PLS-00103: Encountered the symbol "CREATE"
I am hoping that it is possible to do this. Thank you very much for your time and interest =)
Add a forward slash on a new line after each trigger to execute the command in the buffer:
create trigger...
...
end;
/
Put a slash '/' as the first character on a blank line between each trigger statement. This is the SQL*PLUS equivalent of 'go'.
Yes we can execute multiple procedure/trigger/function in single script using the FORWARD SLASH / inside the sql file.
Like below:
create or replace trigger "BI_TEC_ROLES"
before insert on "TEC_ROLES"
for each row
begin
if :NEW."ROLE_ID" is null then
select "TEC_ROLES_SEQ".nextval into :NEW."ROLE_ID" from dual;
end if;
end;
/
create or replace trigger "BI_TEC_STATUSES"
before insert on "TEC_STATUSES"
for each row
begin
if :NEW."STATUS_ID" is null then
select "TEC_STATUSES_SEQ".nextval into :NEW."STATUS_ID" from dual;
end if;
end;
/
create or replace trigger "BI_TEC_SUBS"
before insert on "TEC_SUBS"
for each row
begin
if :NEW."SUB_ID" is null then
select "TEC_SUBS_SEQ".nextval into :NEW."SUB_ID" from dual;
end if;
end;
/
Then oracle will consider it as new statement/block.
Place a forward slash
/
between the two statements on a separate line.
Oracle will then accept it as a new statement
--Parameter:
-- #InclDrop bit
-- Possible values
-- 0 - Script to drop the triggers is not generated.
-- 1 - Script to drip the triggers is generated.
SET ansi_nulls ON
go
SET quoted_identifier ON
go
ALTER PROCEDURE [dbo].[Createscriptofalltriggers]
#InclDrop BIT =1
AS
DECLARE #SQL VARCHAR(8000),
#Text NVARCHAR(4000),
#BlankSpaceAdded INT,
#BasePos INT,
#CurrentPos INT,
#TextLength INT,
#LineId INT,
#MaxID INT,
#AddOnLen INT,
#LFCR INT,
#DefinedLength INT,
#SyscomText NVARCHAR(4000),
#Line NVARCHAR(1000),
#UserName SYSNAME,
#ObjID INT,
#OldTrigID INT
SET nocount ON
SET #DefinedLength = 1000
SET #BlankSpaceAdded = 0
IF #InclDrop <> 0
SET #InclDrop =1
-- This Part Validated the Input parameters
DECLARE #Triggers TABLE
(
username SYSNAME NOT NULL,
trigname SYSNAME NOT NULL,
objid INT NOT NULL
)
DECLARE #TrigText TABLE
(
objid INT NOT NULL,
lineid INT NOT NULL,
linetext NVARCHAR(1000) NULL
)
INSERT INTO #Triggers
(username,
trigname,
objid)
SELECT DISTINCT A.NAME,
B.NAME,
B.id
FROM dbo.sysusers A,
dbo.sysobjects B,
dbo.syscomments C
WHERE A.uid = B.uid
AND B.type = 'Tr'
AND B.id = C.id
AND C.encrypted = 0
IF EXISTS(SELECT C.*
FROM syscomments C,
sysobjects O
WHERE O.id = C.id
AND O.type = 'Tr'
AND C.encrypted = 1)
BEGIN
PRINT '/*'
PRINT 'The following encrypted triggers were found'
PRINT 'The procedure could not write the script for it'
SELECT DISTINCT A.NAME,
B.NAME,
B.id
FROM dbo.sysusers A,
dbo.sysobjects B,
dbo.syscomments C
WHERE A.uid = B.uid
AND B.type = 'Tr'
AND B.id = C.id
AND C.encrypted = 1
PRINT '*/'
END
DECLARE ms_crs_syscom CURSOR local forward_only FOR
SELECT T.objid,
C.text
FROM #Triggers T,
dbo.syscomments C
WHERE T.objid = C.id
ORDER BY T.objid,
C.colid
FOR READ only
SELECT #LFCR = 2
SELECT #LineId = 1
OPEN ms_crs_syscom
SET #OldTrigID = -1
FETCH next FROM ms_crs_syscom INTO #ObjID, #SyscomText
WHILE ##fetch_status = 0
BEGIN
SELECT #BasePos = 1
SELECT #CurrentPos = 1
SELECT #TextLength = Len(#SyscomText)
IF #ObjID <> #OldTrigID
BEGIN
SET #LineID = 1
SET #OldTrigID = #ObjID
END
WHILE #CurrentPos != 0
BEGIN
--Looking for end of line followed by carriage return
SELECT #CurrentPos = Charindex(Char(13) + Char(10), #SyscomText,
#BasePos)
--If carriage return found
IF #CurrentPos != 0
BEGIN
WHILE ( Isnull(Len(#Line), 0) + #BlankSpaceAdded
+ #CurrentPos - #BasePos + #LFCR ) >
#DefinedLength
BEGIN
SELECT #AddOnLen = #DefinedLength - (
Isnull(Len(#Line),
0
) +
#BlankSpaceAdded )
INSERT #TrigText
VALUES ( #ObjID,
#LineId,
Isnull(#Line, N'')
+ Isnull(Substring(#SyscomText, #BasePos,
#AddOnLen),
N''))
SELECT #Line = NULL,
#LineId = #LineId + 1,
#BasePos = #BasePos + #AddOnLen,
#BlankSpaceAdded = 0
END
SELECT #Line = Isnull(#Line, N'')
+ Isnull(Substring(#SyscomText, #BasePos,
#CurrentPos
-#BasePos +
#LFCR),
N'')
SELECT #BasePos = #CurrentPos + 2
INSERT #TrigText
VALUES( #ObjID,
#LineId,
#Line )
SELECT #LineId = #LineId + 1
SELECT #Line = NULL
END
ELSE
--else carriage return not found
BEGIN
IF #BasePos <= #TextLength
BEGIN
/*If new value for #Lines length will be > then the
**defined length
*/
WHILE ( Isnull(Len(#Line), 0) + #BlankSpaceAdded
+ #TextLength - #BasePos + 1 ) >
#DefinedLength
BEGIN
SELECT #AddOnLen = #DefinedLength - (
Isnull(Len(#Line),
0
) +
#BlankSpaceAdded )
INSERT #TrigText
VALUES ( #ObjID,
#LineId,
Isnull(#Line, N'')
+ Isnull(Substring(#SyscomText,
#BasePos,
#AddOnLen),
N''))
SELECT #Line = NULL,
#LineId = #LineId + 1,
#BasePos = #BasePos + #AddOnLen,
#BlankSpaceAdded = 0
END
SELECT #Line = Isnull(#Line, N'')
+ Isnull(Substring(#SyscomText,
#BasePos,
#TextLength
-#BasePos+1
), N'')
IF Len(#Line) < #DefinedLength
AND Charindex(' ', #SyscomText, #TextLength + 1)
> 0
BEGIN
SELECT #Line = #Line + ' ',
#BlankSpaceAdded = 1
END
END
END
END
FETCH next FROM ms_crs_syscom INTO #ObjID, #SyscomText
END
IF #Line IS NOT NULL
INSERT #TrigText
VALUES( #ObjID,
#LineId,
#Line )
CLOSE ms_crs_syscom
PRINT '-- You should run this result under dbo if your triggers belong to multiple users'
PRINT ''
IF #InclDrop = 1
BEGIN
PRINT '-- Dropping the Triggers'
PRINT ''
SELECT 'If exists(Select * from sysObjects where id =Object_ID(''['
+ username + '].[' + trigname
+ ']'') and ObjectProperty(Object_ID(''['
+ username + '].[' + trigname + ']''), ''ISTRIGGER'')=1) Drop Trigger ['
+ username + '].[' + trigname + '] ' + Char(13)
+ Char(10) + 'GO' + Char(13) + Char(10) + Char(13)
+ Char(10)
FROM #Triggers
END
PRINT '----------------------------------------------'
PRINT '-- Creation of Triggers'
PRINT ''
PRINT ''
DECLARE ms_users CURSOR local forward_only FOR
SELECT T.username,
T.objid,
Max(D.lineid)
FROM #Triggers T,
#TrigText D
WHERE T.objid = D.objid
GROUP BY T.username,
T.objid
FOR READ only
OPEN ms_users
FETCH next FROM ms_users INTO #UserName, #ObjID, #MaxID
WHILE ##fetch_status = 0
BEGIN
PRINT 'SetUser N''' + #UserName + '''' + Char(13)
+ Char(10)
SELECT '-- Text of the Trigger'= CASE lineid
WHEN 1 THEN 'GO' + Char(13) + Char(
10)
+
linetext
WHEN #MaxID THEN linetext + 'GO'
ELSE linetext
END
FROM #TrigText
WHERE objid = #ObjID
ORDER BY lineid
PRINT 'Setuser'
FETCH next FROM ms_users INTO #UserName, #ObjID, #MaxID
END
CLOSE ms_users
PRINT 'GO'
PRINT '------End ------'
DEALLOCATE ms_crs_syscom
DEALLOCATE ms_users
SET nocount ON
DECLARE #return_value INT
How to execute it:
EXEC #return_value = [dbo].[Createscriptofalltriggers]
#InclDrop = 1
SELECT 'Return Value' = #return_value
go