SELECT sqltext.TEXT,
req.session_id,
req.status,req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
create proc [dbo].uspRandChars @len int=6, @min tinyint = 48, @range tinyint = 74, @exclude varchar(50) = '0:;<=>?@O[]`^\/', @output varchar(50) output as declare @char char set @output = '' while @len > 0 begin select @char = char(round(rand() * @range + @min, 0)) if charindex(@char, @exclude) = 0 begin set @output += @char set @len = @len - 1 end end ; go
declare @newpwd varchar(20) -- all values between ASCII code 48 - 122 excluding defaults exec [dbo].uspRandChars @len=8, @output=@newpwd out select @newpwd -- all lower case letters excluding o and l exec [dbo].uspRandChars @len=10, @min=97, @range=25, @exclude='ol', @output=@newpwd out select @newpwd -- all upper case letters excluding O exec [dbo].uspRandChars @len=12, @min=65, @range=25, @exclude='O', @output=@newpwd out select @newpwd -- all numbers between 0 and 9 exec [dbo].uspRandChars @len=14, @min=48, @range=9, @exclude='', @output=@newpwd out select @newpwd
USE encrypt_test; GO -- Create Table CREATE TABLE dbo.Customer_data (Customer_id int constraint Pkey3 Primary Key NOT NULL, Customer_Name varchar(100) NOT NULL, Credit_card_number varchar(25) NOT NULL) -- Populate Table INSERT INTO dbo.Customer_data VALUES (74112,'MSSQLTips2','2147-4574-8475') GO INSERT INTO dbo.Customer_data VALUES (74113,'MSSQLTips3','4574-8475-2147') GO INSERT INTO dbo.Customer_data VALUES (74114,'MSSQLTips4','2147-8475-4574') GO INSERT INTO dbo.Customer_data VALUES (74115,'MSSQLTips5','2157-1544-8875') GO -- Verify data SELECT * FROM dbo.Customer_data GO
USE master; GO SELECT * FROM sys.symmetric_keys WHERE name = '##MS_ServiceMasterKey##'; GO
-- Create database Key USE encrypt_test; GO CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Password123'; GO
-- Create self signed certificate USE encrypt_test; GO CREATE CERTIFICATE Certificate1 WITH SUBJECT = 'Protect Data'; GO
-- Create symmetric Key USE encrypt_test; GO CREATE SYMMETRIC KEY SymmetricKey1 WITH ALGORITHM = AES_128 ENCRYPTION BY CERTIFICATE Certificate1; GO
USE encrypt_test; GO ALTER TABLE Customer_data ADD Credit_card_number_encrypt varbinary(MAX) NULL GO
-- Populating encrypted data into new column USE encrypt_test; GO -- Opens the symmetric key for use OPEN SYMMETRIC KEY SymmetricKey1 DECRYPTION BY CERTIFICATE Certificate1; GO UPDATE Customer_data SET Credit_card_number_encrypt = EncryptByKey (Key_GUID('SymmetricKey1'),Credit_card_number) FROM dbo.Customer_data; GO -- Closes the symmetric key CLOSE SYMMETRIC KEY SymmetricKey1; GO
USE encrypt_test; GO ALTER TABLE Customer_data DROP COLUMN Credit_card_number; GO
USE encrypt_test; GO OPEN SYMMETRIC KEY SymmetricKey1 DECRYPTION BY CERTIFICATE Certificate1; GO -- Now list the original ID, the encrypted ID SELECT Customer_id, Credit_card_number_encrypt AS 'Encrypted Credit Card Number', CONVERT(varchar, DecryptByKey(Credit_card_number_encrypt)) AS 'Decrypted Credit Card Number' FROM dbo.Customer_data; -- Close the symmetric key CLOSE SYMMETRIC KEY SymmetricKey1; GO
USE encrypt_test; GO OPEN SYMMETRIC KEY SymmetricKey1 DECRYPTION BY CERTIFICATE Certificate1; -- Performs the update of the record INSERT INTO dbo.Customer_data (Customer_id, Customer_Name, Credit_card_number_encrypt) VALUES (25665, 'mssqltips4', EncryptByKey( Key_GUID('SymmetricKey1'), CONVERT(varchar,'4545-58478-1245') ) ); GO
Execute as user='test' GO SELECT Customer_id, Credit_card_number_encrypt AS 'Encrypted Credit Card Number', CONVERT(varchar, DecryptByKey(Credit_card_number_encrypt)) AS 'Decrypted Credit Card Number' FROM dbo.Customer_data;
GRANT VIEW DEFINITION ON SYMMETRIC KEY::SymmetricKey1 TO test; GO GRANT VIEW DEFINITION ON Certificate::Certificate1 TO test; GO
/****** Object: StoredProcedure [dbo].[spFileDetails] Script Date: 03/28/2007 15:28:15 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[spFileDetails] @Filename VARCHAR(100) /* spFileDetails 'c:\autoexec.bat' */ AS DECLARE @hr INT, --the HRESULT returned from @objFileSystem INT, --the FileSystem object @objFile INT, --the File object @ErrorObject INT, --the error object @ErrorMessage VARCHAR(255),--the potential error message @Path VARCHAR(100),-- @ShortPath VARCHAR(100), @Type VARCHAR(100), @DateCreated datetime, @DateLastAccessed datetime, @DateLastModified datetime, @Attributes INT, @size INT SET nocount ON SELECT @hr=0,@errorMessage='opening the file system object ' EXEC @hr = sp_OACreate 'Scripting.FileSystemObject', @objFileSystem OUT IF @hr=0 SELECT @errorMessage='accessing the file ''' +@Filename+'''', @ErrorObject=@objFileSystem IF @hr=0 EXEC @hr = sp_OAMethod @objFileSystem, 'GetFile', @objFile out,@Filename IF @hr=0 SELECT @errorMessage='getting the attributes of ''' +@Filename+'''', @ErrorObject=@objFile IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'Path', @path OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'ShortPath', @ShortPath OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'Type', @Type OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'DateCreated', @DateCreated OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'DateLastAccessed', @DateLastAccessed OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'DateLastModified', @DateLastModified OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'Attributes', @Attributes OUT IF @hr=0 EXEC @hr = sp_OAGetProperty @objFile, 'size', @size OUT IF @hr<>0 BEGIN DECLARE @Source VARCHAR(255), @Description VARCHAR(255), @Helpfile VARCHAR(255), @HelpID INT EXECUTE sp_OAGetErrorInfo @errorObject, @source output,@Description output, @Helpfile output,@HelpID output SELECT @ErrorMessage='Error whilst ' +@Errormessage+', ' +@Description RAISERROR (@ErrorMessage,16,1) END EXEC sp_OADestroy @objFileSystem EXEC sp_OADestroy @objFile SELECT [Path]= @Path, [ShortPath]= @ShortPath, [Type]= @Type, [DateCreated]= @DateCreated , [DateLastAccessed]= @DateLastAccessed, [DateLastModified]= @DateLastModified, [Attributes]= @Attributes, [size]= @size RETURN @hr
alter PROCEDURE spWriteStringToFile ( @String Varchar(max), --8000 in SQL Server 2000 @Path VARCHAR(255), @Filename VARCHAR(100) -- ) AS DECLARE @objFileSystem int ,@objTextStream int, @objErrorObject int, @strErrorMessage Varchar(1000), @Command varchar(1000), @hr int, @fileAndPath varchar(80) set nocount on select @strErrorMessage='opening the File System Object' EXECUTE @hr = sp_OACreate 'Scripting.FileSystemObject' , @objFileSystem OUT Select @FileAndPath=@path+'\'+@filename if @HR=0 Select @objErrorObject=@objFileSystem , @strErrorMessage='Creating file "'+@FileAndPath+'"' if @HR=0 execute @hr = sp_OAMethod @objFileSystem , 'CreateTextFile' , @objTextStream OUT, @FileAndPath,2,True if @HR=0 Select @objErrorObject=@objTextStream, @strErrorMessage='writing to the file "'+@FileAndPath+'"' if @HR=0 execute @hr = sp_OAMethod @objTextStream, 'Write', Null, @String if @HR=0 Select @objErrorObject=@objTextStream, @strErrorMessage='closing the file "'+@FileAndPath+'"' if @HR=0 execute @hr = sp_OAMethod @objTextStream, 'Close' if @hr<>0 begin Declare @Source varchar(255), @Description Varchar(255), @Helpfile Varchar(255), @HelpID int EXECUTE sp_OAGetErrorInfo @objErrorObject, @source output,@Description output,@Helpfile output,@HelpID output Select @strErrorMessage='Error whilst ' +coalesce(@strErrorMessage,'doing something') +', '+coalesce(@Description,'') raiserror (@strErrorMessage,16,1) end EXECUTE sp_OADestroy @objTextStream EXECUTE sp_OADestroy @objTextStream
ALTER FUNCTION [dbo].[ufsReadfileAsString] ( @Path VARCHAR(255), @Filename VARCHAR(100) ) RETURNS Varchar(max) AS BEGIN DECLARE @objFileSystem int ,@objTextStream int, @objErrorObject int, @strErrorMessage Varchar(1000), @Command varchar(1000), @Chunk Varchar(8000), @String varchar(max), @hr int, @YesOrNo int Select @String='' select @strErrorMessage='opening the File System Object' EXECUTE @hr = sp_OACreate 'Scripting.FileSystemObject' , @objFileSystem OUT if @HR=0 Select @objErrorObject=@objFileSystem, @strErrorMessage='Opening file "'+@path+'\'+@filename+'"',@command=@path+'\'+@filename if @HR=0 execute @hr = sp_OAMethod @objFileSystem , 'OpenTextFile' , @objTextStream OUT, @command,1,false,0--for reading, FormatASCII WHILE @hr=0 BEGIN if @HR=0 Select @objErrorObject=@objTextStream, @strErrorMessage='finding out if there is more to read in "'+@filename+'"' if @HR=0 execute @hr = sp_OAGetProperty @objTextStream, 'AtEndOfStream', @YesOrNo OUTPUT IF @YesOrNo<>0 break if @HR=0 Select @objErrorObject=@objTextStream, @strErrorMessage='reading from the output file "'+@filename+'"' if @HR=0 execute @hr = sp_OAMethod @objTextStream, 'Read', @chunk OUTPUT,4000 SELECT @String=@string+@chunk end if @HR=0 Select @objErrorObject=@objTextStream, @strErrorMessage='closing the output file "'+@filename+'"' if @HR=0 execute @hr = sp_OAMethod @objTextStream, 'Close' if @hr<>0 begin Declare @Source varchar(255), @Description Varchar(255), @Helpfile Varchar(255), @HelpID int EXECUTE sp_OAGetErrorInfo @objErrorObject, @source output,@Description output,@Helpfile output,@HelpID output Select @strErrorMessage='Error whilst ' +coalesce(@strErrorMessage,'doing something') +', '+coalesce(@Description,'') select @String=@strErrorMessage end EXECUTE sp_OADestroy @objTextStream -- Fill the table variable with the rows for your result set RETURN @string END
STUFF(character_expression1, start, length, character_expression2)
Character_Expression1
represents the string in which the stuff is to be applied. start
indicates the starting position of the character in character_expression1
, length
is the length of characters which need to be replaced. character_expression2 is the string that will be replaced to the start position.waitfor delay '0:0:5'
if (is_srvrolemember('sysadmin') > 0) waitfor delay '0:0:5'
if (ascii(substring(@string, @byte, 1)) & (power(2, @bit))) > 0 waitfor delay '0:0:5'
will trigger a delay only if the bit (@bit) of byte (@byte) in the string (@string) is set to 1. To retrieve the current database name from the server, execute
declare @string varchar(8192) select @string = db_name() if (ascii(substring(@string, 1, 1)) & (power(2, 0))) > 0 waitfor delay '0:0:5'This will delay if the first bit of the first byte of the current database name is set to 1. The second bit of the first byte can then be queried:
declare @string varchar(8192) select @string = db_name() if (ascii(substring(@string, 1, 1)) & (power(2, 1))) > 0 waitfor delay '0:0:5'
and so on, building up the entire string. Obviously using this method, this would be a time-consuming process, mainly because of the five-second delay per set bit. It is not necessary, however, to run these queries sequentially or in any particular order. A small program, known as a harness, can be used to form the URLs to request with the necessary injected SQL to build the required string. Multiple requests can then be made to the server in multiple threads, and the harness program can then wait for the requests to return and build the string as they do.
aspnet_regsql.exe -ssadd -sstype:p -S [myserver] -U [mylogin] -P [mypassword]
The parameters are case sensitive. This will create the ASPState database on the specified server. You could use the parameter -E instead of the -U and -P parameters to use the current credentials.SET SAFETY
lines if your mirror is using Synchronous mode. You can check the mode being used in the Mirror Properties (right-click Database, Mirror).--Run on principal
USE master
GO
ALTER DATABASE dbName SET SAFETY FULL
GO
ALTER DATABASE dbName SET PARTNER FAILOVER
GO
--Run on new principal
USE master
GO
ALTER DATABASE dbName SET SAFETY OFF
GO
--Run on mirror if principal isn't available
USE
master
GO
ALTER DATABASE dbName SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS
GO
For example, in a production environment, you'll have a monitoring system which checks for the availability of the Principal at regular intervals. If it detects that the database is unavailable, then it could run a VBScript or a USQL command line to execute this T-SQL on the mirror database. If you have a witness server, then this will be done automatically.<sessionState
key to the following (or if it doesn't exist, add it):<sessionState mode="SQLServer" allowCustomSqlDatabase="true"
sqlConnectionString="data source=[PRINCIPALSERVER];
failover partner=[MIRRORSERVER];initial catalog=ASPState;user id=[DBUSER];
password=[DBPWD];network=dbmssocn;" cookieless="false" timeout="180" />
data source = [PRINCIPALSERVER]
- For data source, add the IP address or name of the Principal server. This is a required parameter.failover partner = [MIRRORPARTNER]
- Specify the name of the Mirror server. This is a required parameter.initial catalog = ASPState
- or specify the name of your database if doing a custom database. This is a required parameter.allowCustomSqlDatabase = "true"
- This is a required parameter.try...catch
around the database connection, and in the catch
, it retries using the mirrored server.SessionState
entry on to each of the web servers.<machineKey
validationKey="D581FCFD1xxxxxxxxxxxxxx16FEEBB4C56Axxxxxxxxxxxxxxxxxxxxxxxxxx"
decryptionKey="55B44F83Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
validation="SHA1" decryption="AES"
/>
"Cannot alter database <db>because the database is not in the correct state
to become the principal"
You'll be able to perform a manual failover fine, but forced failovers will cause the error. The mirror will NOT become the principal if it detects that the principal is already running. This may happen if you are testing a forced failover with code or a script and don't stop the SQL instance on the principal. If you stop the service on the principal, you can then perform a forced failover. "Remote copy of <db>has not been rolled forward to a point in time
that is encompassed in the local copy of the database. Error: 1402"
This will occur if you have not done a transaction log backup on the Principal and restored it (no recovery) on the Mirror. You MUST do this step, or this error will occur.
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
DECLARE @TmpTable TABLE (ID INT, TEXTVal VARCHAR(100))
INSERT TestTable (ID, TEXTVal)
OUTPUT Inserted.ID, Inserted.TEXTVal INTO @TmpTable
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
OUTPUT Inserted.ID, Inserted.TEXTVal INTO @TmpTable
VALUES (2,'SecondVal')
SELECT * FROM @TmpTable
SELECT * FROM TestTable
UPDATE STATEMENT
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
CREATE TABLE BAK_TestTable (Old_ID INT, Old_TEXTVal VARCHAR(100),
New_ID INT, New_TEXTVal VARCHAR(100)
,Date DATETIME)
update TestTable set id=6 ,textval='Dinesh'
output deleted.ID,deleted.textval,
inserted.id,inserted.textval,
getdate() into BAK_
TestTable
where id=2
DELETE STATEMENT
DELETE FROM
TestTable
OUTPUT Deleted.*
Where id=6
C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA
sqlcmd -S .\SQLEXPRESS -i "C:\Users\Administrator\Documents\Backup.sql"
schtasks /create /sc Daily /st 03:30:00 /tn "MyTask" /tr "cmd /c C:\Users\Administrator\Desktop\Backup.bat"
CREATE PROCEDURE crosstab @select varchar(8000), @sumfunc varchar(100), @pivot varchar(100), @table varchar(100) AS DECLARE @sql varchar(8000), @delim varchar(1) SET NOCOUNT ON SET ANSI_WARNINGS OFF EXEC ('SELECT ' + @pivot + ' AS pivot INTO ##pivot FROM ' + @table + ' WHERE 1=2') EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE ' + @pivot + ' Is Not Null') SELECT @sql='', @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' ) SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) ) WHEN 0 THEN '' ELSE '''' END FROM tempdb.information_schema.columns WHERE table_name='##pivot' AND column_name='pivot' SELECT @sql=@sql + '''' + convert(varchar(100), pivot) + ''' = ' + stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' + @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM ##pivot DROP TABLE ##pivot SELECT @sql=left(@sql, len(@sql)-1) SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ') EXEC (@select) SET ANSI_WARNINGS ONYeah, I know, you want to know how it works :) I won't go into detail on the mechanics of the code. Let's just say that if you can follow it, feel free to play with it; if not, DON'T TOUCH IT! The syntax for the procedure call is below, followed by a description of each parameter:
1 | 2 | 3 | 4 | |
EXECUTE crosstab | SELECT statement, | summary calculation, | pivot column, | table name |
EXECUTE crosstab 'select title from titles inner join sales on (sales.title_id=titles.title_id) group by title', 'sum(qty)','stor_id','stores'
title | 6380 | 7066 | 7067 | 7131 | 7896 | 8042 |
But Is It User Friendly? | 30 | |||||
Computer Phobic AND Non-Phobic Individuals: Behavior Variations | 20 | |||||
Cooking with Computers: Surreptitious Balance Sheets | 25 | |||||
Emotional Security: A New Algorithm | 25 | |||||
Fifty Years in Buckingham Palace Kitchens | 20 | |||||
Is Anger the Enemy? | 3 | 75 | 10 | 20 | ||
Life Without Fear | 25 | |||||
Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean | 40 | |||||
Prolonged Data Deprivation: Four Case Studies | 15 | |||||
Secrets of Silicon Valley | 50 | |||||
Silicon Valley Gastronomic Treats | 10 | |||||
Straight Talk About Computers | 15 | |||||
Sushi, Anyone? | 20 | |||||
The Busy Executive's Database Guide | 5 | 10 | ||||
The Gourmet Microwave | 25 | 15 | ||||
You Can Combat Computer Stress! | 35 |
EXECUTE crosstab 'select pub_name, count(qty) as orders, sum(qty) as total from sales inner join titles on (sales.title_id=titles.title_id) right join publishers on (publishers.pub_id=titles.pub_id) group by pub_name', 'sum(qty)','type','titles'
pub_name | orders | total | business | mod_cook | popular_comp | psychology | trad_cook | UNDECIDED |
Algodata Infosystems | 6 | 135 | 55 | 80 | ||||
Binnet & Hardley | 7 | 150 | 50 | 20 | 80 | |||
Five Lakes Publishing | 0 | |||||||
GGG&G | 0 | |||||||
Lucerne Publishing | 0 | |||||||
New Moon Books | 8 | 208 | 35 | 173 | ||||
Ramona Publishers | 0 | |||||||
Scootney Books | 0 |
EXECUTE crosstab 'SELECT LastName FROM Employees INNER JOIN Orders ON (Employees.EmployeeID=Orders.EmployeeID) GROUP BY LastName', 'count(lastname)', 'Year(OrderDate)', 'Orders'
LastName | 1996 | 1997 | 1998 |
Buchanan | 11 | 18 | 13 |
Leverling | 18 | 71 | 38 |
Fuller | 16 | 41 | 39 |
Peacock | 31 | 81 | 44 |
Callahan | 19 | 54 | 31 |
Suyama | 15 | 33 | 19 |
King | 11 | 36 | 25 |
Dodsworth | 5 | 19 | 19 |
Davolio | 26 | 55 | 42 |
SET NOCOUNT ON
GO
DECLARE @path nvarchar(2000), @batchsize nvarchar(40),
@format nvarchar(40), @serverinstance nvarchar(200),
@security nvarchar(800)
SET @path = 'C:\Temp\';
SET @batchsize = '1000000' -- COMMIT EVERY n RECORDS
SET @serverinstance = 'PGALLUCC-M7' --SQL Server \ Instance name
SET @security = ' -T ' -- -T (trusted), -Uloginid -Ploginpassword
--GENERATE CONSTRAINT NO CHECK
PRINT '--NO CHECK CONSTRAINTS'
SELECT 'ALTER TABLE ' + QUOTENAME( TABLE_NAME ) + ' NOCHECK CONSTRAINT '
+ QUOTENAME( CONSTRAINT_NAME )
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--DISABLE TRIGGERS
PRINT '--DISABLE TRIGGERS'
SELECT 'ALTER TABLE ' + QUOTENAME( TABLE_NAME ) + ' DISABLE TRIGGER ALL'
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
--BCP-OUT TABLES
PRINT '--BCP OUT TABLES '
SELECT 'bcp "' + QUOTENAME( TABLE_CATALOG ) + '.' + QUOTENAME( TABLE_SCHEMA )
+ '.' + QUOTENAME( TABLE_NAME ) + '" out "' + @path + '' + TABLE_NAME + '.dat" -q -b"'
+ @batchsize + '" -e"' + @path + '' + TABLE_NAME + '.err" -n -CRAW -o"' + @path + ''
+ TABLE_NAME + '.out" -S"' + @serverinstance + '" ' + @security + ''
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
-- CREATE NON-XML FORMAT FILE
PRINT '--NON-XML FORMAT FILE'
SELECT 'bcp "' + QUOTENAME( TABLE_CATALOG ) + '.' + QUOTENAME( TABLE_SCHEMA ) + '.'
+ QUOTENAME( TABLE_NAME ) + '" format nul -n -CRAW -f "' + @path + ''
+ TABLE_NAME + '.fmt" --S"' + @serverinstance + '" ' + @security + ''
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
-- CREATE XML FORMAT FILE
PRINT '--XML FORMAT FILE'
SELECT 'bcp "' +QUOTENAME( TABLE_CATALOG ) + '.' + QUOTENAME( TABLE_SCHEMA )
+ '.' + QUOTENAME( TABLE_NAME ) + '" format nul -x -n -CRAW -f "'
+ @path + '' + TABLE_NAME + '.xml" -S"' + @serverinstance + '" ' + @security + ''
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
--TRUNCATE TABLE
PRINT '--TRUNCATE TABLE'
SELECT 'TRUNCATE TABLE ' +QUOTENAME( TABLE_NAME ) + '
GO '
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
--BULK INSERT
PRINT '--BULK INSERT'
SELECT DISTINCT 'BULK INSERT ' + QUOTENAME(TABLE_CATALOG) + '.'
+ QUOTENAME( TABLE_SCHEMA ) + '.' + QUOTENAME( TABLE_NAME ) + '
FROM ''' + @path + '' + TABLE_NAME + '.Dat''
WITH (FORMATFILE = ''' + @path + '' + TABLE_NAME + '.FMT'',
BATCHSIZE = ' + @batchsize + ',
ERRORFILE = ''' + @path + 'BI_' + TABLE_NAME + '.ERR'',
TABLOCK);
GO '
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
--OPENROWSET
PRINT '--OPENROWSET'
SELECT DISTINCT 'INSERT INTO ' + QUOTENAME(TABLE_CATALOG) + '.'
+ QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) + '
SELECT *
FROM OPENROWSET(BULK ''' + @path + '' + TABLE_NAME + '.Dat'',
FORMATFILE=''' + @path + '' + TABLE_NAME + '.Xml''
) as t1 ;
GO '
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'
--GENERATE CONSTRAINT CHECK CONSTRAINT TO VERIFY DATA AFTER LOAD
PRINT '--CHECK CONSTRAINT'
SELECT 'ALTER TABLE ' + QUOTENAME( TABLE_NAME ) + ' CHECK CONSTRAINT '
+ QUOTENAME( CONSTRAINT_NAME )
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--ENABLE TRIGGERS
PRINT '--ENABLE TRIGGERS'
SELECT 'ALTER TABLE ' + QUOTENAME( TABLE_NAME ) + ' ENABLE TRIGGER ALL'
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'