Quantcast
Channel: Brad Chen's SQL Server Blog
Viewing all 62 articles
Browse latest View live

Scripting learning resources

$
0
0

Using SQL Server in Windows 8 and later versions of Windows operating system

$
0
0

雖然KB2681562文件說明Windows 10不支援SQL 2008 R2

但經過測試在Windows 10安裝SQL 2008 R2只會跳出警告,最後還是可以安裝成功 ,但此種搭配微軟並不支援,將來也不會有hotfix

Using SQL Server in Windows 8 and later versions of Windows operating system
https://support.microsoft.com/en-us/kb/2681562

OS version SQL version Minimum SQL Server version requirements
Windows 10 SQL 2014 Support SQL Server 2014 Service Pack 1 or a later update
SQL 2012 Support SQL Server 2012 Service Pack 2 or a later update
SQL 2008 R2 Not Support SQL Server 2008 R2 is not supported on Windows 10
SQL 2008 Not Support SQL Server 2008 is not supported on Windows 10
Windows Server 2012 R2 or Windows 8.1 SQL 2014 Support SQL Server 2014 RTM or a later version
SQL 2012 Support SQL Server 2012 Service Pack 1 or a later update
SQL 2008 R2 Support SQL Server 2008 R2 Service Pack 2 or a later update
Support SQL Server 2008 Service Pack 3 or a later update
Windows Server 2012 or Windows 8 SQL 2014 Support SQL Server 2014 RTM or a later version
SQL 2012 Support SQL Server 2012 RTM or a later update
SQL 2008 R2 Support SQL Server 2008 R2 Service Pack 1 or a later update
Support SQL Server 2008 Service Pack 3 or a later update

Microsoft VBScript

$
0
0

Quick Start:

VBScript Operators
https://msdn.microsoft.com/en-us/library/9da4s2eh(v=vs.84).aspx

' String
strMyString = "Line1"
strMyString = strMyString & vbNewLine
strMyString = strMyString & "Line2"
strMyString = strMyString & vbCr & vbLf
strMyString = strMyString & "Line3"
strMyString = strMyString & vbCrLf
strMyString = strMyString & "Line4"
' Date
Dim dteExpiredDate
    dteExpiredDate = "2008/12/31"
    dteExpiredDate = #2008/12/31#              

'Time
Now()
Time()
Hour(Now())
Minute(Now())
Second(Now())
' Constants
Const COMP_NAME = "Microsoft"
Const LOCATION = "Taiwan"
'  Intrinsic Constants (Build-in Constants)
FormatDateTime(Now(),vbShortDate)
FormatDateTime(Now(),vbLongDate)
FormatDateTime(Now(),vbShortTime)
FormatDateTime(Now(),vbLongTime)
' Buildin Datediff Function
DateDiff("d", Now, "2008/05/30")
' Buildin String Function
strMyString = "This is a book."
WScript.Echo "Upper Case : " & UCase(strMyString)
WScript.Echo "Lower Case : " & LCase(strMyString)

LEN(strMyString)
Left(strMyString,4)
Right(strMyString,5)
InStr(strMyString,"is")
InStr(4,strMyString,"is")
' Round
Randomize
vRnd = Rnd * 100
WScript.Echo "vRnd : " & vRnd
WScript.Echo "Round(vRnd) : " & Round(vRnd)
'Conversion Functions
'CInt
Dim MyDouble, MyInt, MyByte, MyString, MyVal1, MyVal2, MyLong1, MyLong2
MyDouble = 2345.5678     ' MyDouble is a Double.
MyInt = CInt(MyDouble)   ' MyInt contains 2346.
'CBytes
MyDouble = 125.5678        ' MyDouble is a Double.
MyByte = CByte(MyDouble)   ' MyByte contains 126.
'CStr
MyDouble = 437.324         ' MyDouble is a Double.
MyString = CStr(MyDouble)   ' MyString contains "437.324".
'CLng
MyVal1 = 25427.45: MyVal2 = 25427.55   ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)   ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)   ' MyLong2 contains 25428.

Using Conditional Statements
https://msdn.microsoft.com/en-us/library/9t9x467f(v=vs.84).aspx

' If Then Else
'    Dim myDate
    myDate = #2/13/95#
    If myDate < Now Then myDate = Now

   If value = 0 Then
      WScript.Echo "value=0"
   ElseIf value = 1 Then
      WScript.Echo "value=1"
   Else
      WScript.Echo "Value out of range!"
   End If

MyVar = 2
Select Case MyVar
 Case "0"
  WScript.Echo "MyVar = 0"
 Case "1"
  WScript.Echo "MyVar = 1"
 Case "2"
  WScript.Echo "MyVar = 2"
 Case Else
  WScript.Echo "Sorry value is out of range"
End Select

Looping Through Code
https://msdn.microsoft.com/en-us/library/cbe735w2(v=vs.84).aspx

   For j = 2 To 10 Step 2
      total = total + j
   Next
   For myNum = 16 To 2 Step -2
      total = total + myNum
   Next
   Do While myNum2 > 10
      myNum2 = myNum2 - 1
      counter = counter + 1
   Loop
   Do Until myNum3 = 1
      myNum3 = myNum3 - 1
      counter2 = counter2 + 1
      If myNum3 < 3 Then Exit Do
   Loop
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "0", "Athens"   'Add some keys and items
   d.Add "1", "Belgrade"
   d.Add "2", "Cairo"

   For Each I in d
      WScript.Echo "D.Item(" & I & ") : " & d.Item(I)
   Next
'Array & Dynamic Array
'== 1 Dimension Array ==
Dim Names(9)       ' Declare an array with 10 elements.

'== 2 Dimension Array ==
Dim aryTwoDimension(2,2)

Dim aryTripleDimension
aryTripleDimension = Array(10,20,30)
B = aryTripleDimension(2)   ' B is now 30.

'== Dynamic Array ==
Dim NumArray()
Dim DynamicArray()      ' Declare a dynamic array.
ReDim DynamicArray(9)   ' Allocate storage space.
ReDim Preserve DynamicArray(10)   ' Allocate storage space.

'== Erase Array ==
Erase NumArray          ' Each element is reinitialized.
Erase DynamicArray      ' Free memory used by array.

'== Ubound Function ==
Dim A(100,3,4)
WScript.Echo "UBound(A, 1) : " & UBound(A, 1)
WScript.Echo "UBound(A, 2) : " & UBound(A, 2)
WScript.Echo "UBound(A, 3) : " & UBound(A, 3)

'== Split ==
Dim MyString, MyArray, Msg
MyString = "VBScriptXisXfun!"
MyArray = Split(MyString, "x", -1, 1)
' MyArray(0) contains "VBScript".
' MyArray(1) contains "is".
' MyArray(2) contains "fun!".
Msg = MyArray(0) & " " & MyArray(1)
Msg = Msg   & " " & MyArray(2)
WScript.Echo Msg

'== Is Array ==
Dim MyVariable
Dim MyArray5(3)
MyArray5(0) = "Sunday"
MyArray5(1) = "Monday"
MyArray5(2) = "Tuesday"
MyVariable = IsArray(MyArray5) ' MyVariable contains "True".
WScript.Echo "MyVariable : " & MyVariable

‘ Sub Procedures
https://msdn.microsoft.com/en-us/library/bx9ceb2w(v=vs.84).aspx
Sub Procedures

Sub ConvertTemp
   temp = InputBox("Please enter the temperature in degrees F.", 1)
   MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Function Procedures

Sub ConvertTemp
   temp = InputBox("Please enter the temperature in degrees F.", 1)
   MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Function Celsius(fDegrees)
   Celsius = (fDegrees - 32) * 5 / 9
End Function
'== Pass paremeter ==
WScript.Echo "Gross Value is: " & GrossValue(100,0.175)

Function GrossValue(NetValue, TaxRate)
 GrossValue=NetValue + (NetValue * TaxRate)
End Function
'== Pass array parameter ==
Dim aryDemo(2)
 aryDemo(0) = 1
 aryDemo(1) = 2
 aryDemo(2) = 3

Call PrintArray(aryDemo)

Sub PrintArray(aryParameter)
 
 Dim i
 For i=0 To UBound(aryParameter)
  WScript.Echo "Array(" & i & ") Value Is : " & aryParameter(i)
 Next
 
End Sub
'== Pass Object parameter ==
' List Items in the My Computer Folder
Const MY_COMPUTER = &H11&

Set objShell = CreateObject("Shell.Application")

Call ListItemInMyComputer(objShell)

Sub ListItemInMyComputer(objShellObject)

 Set objFolder = objShellObject.Namespace(MY_COMPUTER)
 Set objFolderItem = objFolder.Self
  WScript.Echo objFolderItem.Path
 
 Set colItems = objFolder.Items
 For Each objItem in colItems
     Wscript.Echo objItem.Name
 Next
 
End Sub

Set objShell = Nothing

Sub TestSub(ByRef MyParam)
    MyParam = 5
End Sub

Dim MyArg
MyArg = 123

TestSub MyArg
' MyArg in changed in TestSub to 5.

Sub TestSub(ByVal MyParam)
    MyParam = 5
End Sub

Dim MyArg
MyArg = 123
TestSub MyArg
' MyArg is still 123.

更多ByRef,ByVal用法請參考
ByRef and ByVal Parameters
https://msdn.microsoft.com/en-us/library/ee478101(v=vs.84).aspx

VBScript:

Script Center > Learn > Learn Beginning Scripting

Class is in Session

Scripting Guide

Download Documents or Tools

VBScript Constants

VBScript Common Constants

VBScript Template
Template – Sample
Security:
vbe file
Script Encoder Overview (Script Encoder is not supported in Windows Vista or Windows 7)
  SCRENC [/s] [/f] [/xl] [/l defLanguage ] [/e defExtension] input file output file

HTML Applications (HTAs):

 

Development Tools for VBScript:

  • Visual Studio
  • Notepad
  • Notepad++ (Third-Party)
  • UltraEdit (Third-Party)
  • VbsEdit (Third-Party)
  • Admin Script Editor (Third-Party)

Code Auto Generator:

VBScript Common Constants

$
0
0

1.FileSystemObject

‘For FileSystemObject
Const ForWriting      = 2
Const ForAppending   = 8
Const ForReading     = 1

Const OpenAsDefault = -2  ‘ Opens the file using the system default.
Const OpenAsUnicode = -1  ‘ Opens the file as Unicode.
Const OpenAsUSAscii =  0  ‘ Opens the file as ASCII.
Const DontCreate =  False ‘ do not create a new file if doesn’t exist
Const CreateFile =  True  ‘ create a new file if the specified filename doesn’t exist

‘Constants returned by File.Attributes
Const FileAttrNormal    = 0
Const FileAttrReadOnly  = 1
Const FileAttrHidden    = 2
Const FileAttrSystem    = 4
Const FileAttrVolume    = 8
Const FileAttrDirectory    = 16
Const FileAttrArchive     = 32
Const FileAttrAlias        = 64
Const FileAttrCompressed = 128

 

2.ADSI

‘ For ADS_PROPERTY_OPERATION_ENUM
ADS_PROPERTY_CLEAR    = 1
ADS_PROPERTY_UPDATE  = 2
ADS_PROPERTY_APPEND  = 3
ADS_PROPERTY_DELETE  = 4

‘For ADS_GROUP_TYPE_ENUM
ADS_GROUP_TYPE_GLOBAL_GROUP         = 0x00000002,
ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP  = 0x00000004,
ADS_GROUP_TYPE_LOCAL_GROUP           = 0x00000004,
ADS_GROUP_TYPE_UNIVERSAL_GROUP      = 0x00000008,
ADS_GROUP_TYPE_SECURITY_ENABLED     = 0x80000000

‘For ADS_USER_FLAG
ADS_UF_ACCOUNTDISABLE             =  0X0002,
ADS_UF_LOCKOUT                      =  0X0010,
ADS_UF_PASSWD_NOTREQD            =  0X0020,
ADS_UF_PASSWD_CANT_CHANGE       =  0X0040,
ADS_UF_DONTEXPIREPASSWD          =  0X10000,
ADS_UF_TRUSTED_FOR_DELEGATION   =  0X80000,
ADS_UF_NOT_DELEGATED              =  0X100000

CONST UF_ACCOUNTDISABLE=&H0002
CONST UF_DONT_EXPIRE_PASSWD=&H10000
CONST UF_HOMEDIR_REQUIRED=&H0008
CONST UF_INTERDOMAIN_TRUST_ACCOUNT=&H0800
CONST UF_LOCKOUT=&H0010
CONST UF_MNS_LOGON_ACCOUNT=&H20000
CONST UF_NORMAL_ACCOUNT=&H0200
CONST UF_PASSWD_CANT_CHANGE=&H0040
CONST UF_PASSWD_NOTREQD=&H0020
CONST UF_SCRIPT=&H0001
CONST UF_SERVER_TRUST_ACCOUNT=&H2000
CONST UF_TEMP_DUPLICATE_ACCOUNT=&H0100
CONST UF_WORKSTATION_TRUST_ACCOUNT=&H1000

‘Parameter for search AD
Const ADS_SCOPE_SUBTREE = 2      ‘Subtree
Const ADS_SCOPE_ONELEVEL = 1     ‘Top Level

 

3.Registry

‘For Registry Catalog
Const HKEY_CLASSES_ROOT  = &H80000000
Const HKEY_CURRENT_USER  = &H80000001
Const HKEY_LOCAL_MACHINE  = &H80000002
Const HKEY_USERS        = &H80000003
Const HKEY_CURRENT_CONFIG  = &H80000005

Const HKEY_DYN_DATA       = &H80000006

‘For Registry Type

Const REG_NONE      = 0
Const REG_SZ       = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY      = 3
Const REG_DWORD  = 4
Const REG_MULTI_SZ   = 7

 

4.ADO

‘—- CursorTypeEnum Values —-
Const adOpenForwardOnly = 0
Const adOpenKeyset = 1
Const adOpenDynamic = 2
Const adOpenStatic = 3

‘—- LockTypeEnum Values —-
Const adLockReadOnly = 1
Const adLockPessimistic = 2
Const adLockOptimistic = 3
Const adLockBatchOptimistic = 4

‘—- CursorLocationEnum Values —-
Const adUseServer = 2
Const adUseClient = 3

‘ ADODB

‘ActiveX Data Objects (ADO)
CONST adAddNew=&H01000400
CONST adAffectAllChapters=4
CONST adAffectCurrent=1
CONST adAffectGroup=2
CONST adApproxPosition=&H00004000
CONST adArray=&H2000
CONST adAsyncConnect=&H00000010
CONST adAsyncExecute=&H00000010
CONST adAsyncFetch=&H00000020
CONST adAsyncFetchNonBlocking=&H00000040
CONST adBigInt=20
CONST adBinary=128
CONST adBookmark=&H00002000
CONST adBookmarkCurrent=0
CONST adBookmarkFirst=1
CONST adBookmarkLast=2
CONST adBoolean=11
CONST adBSTR=8
CONST adChapter=136
CONST adChar=129
CONST adClipString=2
CONST adCmdFile=&H0100
CONST adCmdStoredProc=&H0004
CONST adCmdTable=&H0002
CONST adCmdTableDirect=&H0200
CONST adCmdText=&H0001
CONST adCmdUnknown=&H0008
CONST adCollectionRecord=1
CONST adCompareEqual=1
CONST adCompareGreaterThan=2
CONST adCompareLessThan=0
CONST adCompareNotComparable=4
CONST adCompareNotEqual=3
CONST adCopyAllowEmulation=4
CONST adCopyNonRecursive=2
CONST adCopyOverWrite=1
CONST adCopyUnspecified=-1
CONST adCR=13
CONST adCreateCollection=&H00002000
CONST adCreateNonCollection=&H00000000
CONST adCreateOverwrite=&H04000000
CONST adCreateStructDoc=&H80000000
CONST adCriteriaAllCols=1
CONST adCriteriaKey=0
CONST adCriteriaTimeStamp=3
CONST adCriteriaUpdCols=2
CONST adCRLF=-1
CONST adCurrency=6
CONST adDate=7
CONST adDBDate=133
CONST adDBTime=134
CONST adDBTimeStamp=135
CONST adDecimal=14
CONST adDefaultStream=-1
CONST adDelayFetchFields=&H00008000
CONST adDelayFetchStream=&H00004000
CONST adDelete=&H01000800
CONST adDouble=5
CONST adEditAdd=&H0002
CONST adEditDelete=&H0004
CONST adEditInProgress=&H0001
CONST adEditNone=&H0000
CONST adEmpty=0
CONST adErrBoundToCommand=&He7b
CONST adErrCannotComplete=&He94
CONST adErrCantChangeConnection=&Hea4
CONST adErrCantChangeProvider=&Hc94
CONST adErrCantConvertvalue=&He8c
CONST adErrCantCreate=&He8d
CONST adErrCatalogNotSet=&Hea3
CONST adErrColumnNotOnThisRow=&He8e
CONST adErrDataConversion=&Hd5d
CONST adErrDataOverflow=&He89
CONST adErrDelResOutOfScope=&He9a
CONST adErrDenyNotSupported=&Hea6
CONST adErrDenyTypeNotSupported=&Hea7
CONST adErrFeatureNotAvailable=&Hcb3
CONST adErrFieldsUpdateFailed=&Hea5
CONST adErrIllegalOperation=&Hc93
CONST adErrIntegrityViolation=&He87
CONST adErrInTransaction=&Hcae
CONST adErrInvalidArgument=&Hbb9
CONST adErrInvalidConnection=&He7d
CONST adErrInvalidParamInfo=&He7c
CONST adErrInvalidTransaction=&He82
CONST adErrInvalidURL=&He91
CONST adErrItemNotFound=&Hcc1
CONST adErrNoCurrentRecord=&Hbcd
CONST adErrNotReentrant=&He7e
CONST adErrObjectClosed=&He78
CONST adErrObjectInCollection=&Hd27
CONST adErrObjectNotSet=&Hd5c
CONST adErrObjectOpen=&He79
CONST adErrOpeningFile=&Hbba
CONST adErrOperationCancelled=&He80
CONST adError=10
CONST adErrOutOfSpace=&He96
CONST adErrPermissionDenied=&He88
CONST adErrPropConflicting=&He9e
CONST adErrPropInvalidColumn=&He9b
CONST adErrPropInvalidOption=&He9c
CONST adErrPropInvalidValue=&He9d
CONST adErrPropNotAllSettable=&He9f
CONST adErrPropNotSet=&Hea0
CONST adErrPropNotSettable=&Hea1
CONST adErrPropNotSupported=&Hea2
CONST adErrProviderFailed=&Hbb8
CONST adErrProviderNotFound=&He7a
CONST adErrReadFile=&Hbbb
CONST adErrResourceExists=&He93
CONST adErrResourceLocked=&He92
CONST adErrResourceOutOfScope=&He97
CONST adErrSchemaViolation=&He8a
CONST adErrSignMismatch=&He8b
CONST adErrStillConnecting=&He81
CONST adErrStillExecuting=&He7f
CONST adErrTreePermissionDenied=&He90
CONST adErrUnavailable=&He98
CONST adErrUnsafeOperation=&He84
CONST adErrURLDoesNotExist=&He8f
CONST adErrURLIntegrViolSetColumns=&He8f
CONST adErrURLNamedRowDoesNotExist=&He99
CONST adErrVolumeNotFound=&He95
CONST adErrWriteFile=&Hbbc
CONST adExecuteNoRecords=&H00000080
CONST adFailIfNotExists=-1
CONST adFieldAlreadyExists=26
CONST adFieldBadStatus=12
CONST adFieldCannotComplete=20
CONST adFieldCannotDeleteSource=23
CONST adFieldCantConvertValue=2
CONST adFieldCantCreate=7
CONST adFieldDataOverflow=6
CONST adFieldDefault=13
CONST adFieldDoesNotExist=16
CONST adFieldIgnore=15
CONST adFieldIntegrityViolation=10
CONST adFieldInvalidURL=17
CONST adFieldIsNull=3
CONST adFieldOK=0
CONST adFieldOutOfSpace=22
CONST adFieldPendingChange=&H40000
CONST adFieldPendingDelete=&H20000
CONST adFieldPendingInsert=&H10000
CONST adFieldPendingUnknown=&H80000
CONST adFieldPendingUnknownDelete=&H100000
CONST adFieldPermissionDenied=9
CONST adFieldReadOnly=24
CONST adFieldResourceExists=19
CONST adFieldResourceLocked=18
CONST adFieldResourceOutOfScope=25
CONST adFieldSchemaViolation=11
CONST adFieldSignMismatch=5
CONST adFieldTruncated=4
CONST adFieldUnavailable=8
CONST adFieldVolumeNotFound=21
CONST adFileTime=64
CONST adFilterAffectedRecords=2
CONST adFilterConflictingRecords=5
CONST adFilterFetchedRecords=3
CONST adFilterNone=0
CONST adFilterPendingRecords=1
CONST adFind=&H00080000
CONST adFldCacheDeferred=&H00001000
CONST adFldFixed=&H00000010
CONST adFldIsChapter=&H00002000
CONST adFldIsCollection=&H00040000
CONST adFldIsDefaultStream=&H00020000
CONST adFldIsNullable=&H00000020
CONST adFldIsRowURL=&H00010000
CONST adFldKeyColumn=&H00008000
CONST adFldLong=&H00000080
CONST adFldMayBeNull=&H00000040
CONST adFldMayDefer=&H00000002
CONST adFldNegativeScale=&H00004000
CONST adFldRowID=&H00000100
CONST adFldRowVersion=&H00000200
CONST adFldUnknownUpdatable=&H00000008
CONST adFldUpdatable=&H00000004
CONST adGetRowsRest=-1
CONST adGUID=72
CONST adHoldRecords=&H00000100
CONST adIDispatch=9
CONST adIndex=&H00800000
CONST adInteger=3
CONST adIUnknown=13
CONST adLF=10
CONST adLockBatchOptimistic=4
CONST adLockOptimistic=3
CONST adLockPessimistic=2
CONST adLockReadOnly=1
CONST adLongVarBinary=205
CONST adLongVarChar=201
CONST adLongVarWChar=203
CONST adMarshalAll=0
CONST adMarshalModifiedOnly=1
CONST adModeRead=1
CONST adModeReadWrite=3
CONST adModeRecursive=&H400000
CONST adModeShareDenyNone=&H10
CONST adModeShareDenyRead=4
CONST adModeShareDenyWrite=8
CONST adModeShareExclusive=&Hc
CONST adModeUnknown=0
CONST adModeWrite=2
CONST adMoveAllowEmulation=4
CONST adMoveDontUpdateLinks=2
CONST adMoveOverWrite=1
CONST adMovePrevious=&H00000200
CONST adMoveUnspecified=-1
CONST adNotify=&H00040000
CONST adNumeric=131
CONST adOpenAsync=&H00001000
CONST adOpenDynamic=2
CONST adOpenForwardOnly=0
CONST adOpenIfExists=&H02000000
CONST adOpenKeyset=1
CONST adOpenRecordUnspecified=-1
CONST adOpenSource=&H00800000
CONST adOpenStatic=3
CONST adOpenStreamAsync=1
CONST adOpenStreamFromRecord=4
CONST adOpenStreamUnspecified=-1
CONST adParamInput=&H0001
CONST adParamInputOutput=&H0003
CONST adParamLong=&H0080
CONST adParamNullable=&H0040
CONST adParamOutput=&H0002
CONST adParamReturnValue=&H0004
CONST adParamSigned=&H0010
CONST adParamUnknown=&H0000
CONST adPersistADTG=0
CONST adPersistXML=1
CONST adPosBOF=-2
CONST adPosEOF=-3
CONST adPosUnknown=-1
CONST adPriorityAboveNormal=4
CONST adPriorityBelowNormal=2
CONST adPriorityHighest=5
CONST adPriorityLowest=1
CONST adPriorityNormal=3
CONST adPromptAlways=1
CONST adPromptComplete=2
CONST adPromptCompleteRequired=3
CONST adPromptNever=4
CONST adPropNotSupported=&H0000
CONST adPropOptional=&H0002
CONST adPropRead=&H0200
CONST adPropRequired=&H0001
CONST adPropVariant=138
CONST adPropWrite=&H0400
CONST adReadAll=-1
CONST adReadLine=-2
CONST adRecalcAlways=1
CONST adRecalcUpFront=0
CONST adRecCanceled=&H0000100
CONST adRecCantRelease=&H0000400
CONST adRecConcurrencyViolation=&H0000800
CONST adRecDBDeleted=&H0040000
CONST adRecDeleted=&H0000004
CONST adRecIntegrityViolation=&H0001000
CONST adRecInvalid=&H0000010
CONST adRecMaxChangesExceeded=&H0002000
CONST adRecModified=&H0000002
CONST adRecMultipleChanges=&H0000040
CONST adRecNew=&H0000001
CONST adRecObjectOpen=&H0004000
CONST adRecOK=&H0000000
CONST adRecordURL=-2
CONST adRecOutOfMemory=&H0008000
CONST adRecPendingChanges=&H0000080
CONST adRecPermissionDenied=&H0010000
CONST adRecSchemaViolation=&H0020000
CONST adRecUnmodified=&H0000008
CONST adResync=&H00020000
CONST adResyncAllValues=2
CONST adResyncUnderlyingValues=1
CONST adRsnAddNew=1
CONST adRsnClose=9
CONST adRsnDelete=2
CONST adRsnFirstChange=11
CONST adRsnMove=10
CONST adRsnMoveFirst=12
CONST adRsnMoveLast=15
CONST adRsnMoveNext=13
CONST adRsnMovePrevious=14
CONST adRsnRequery=7
CONST adRsnResynch=8
CONST adRsnUndoAddNew=5
CONST adRsnUndoDelete=6
CONST adRsnUndoUpdate=4
CONST adRsnUpdate=3
CONST adSaveCreateNotExist=1
CONST adSaveCreateOverWrite=2
CONST adSchemaAsserts=0
CONST adSchemaCatalogs=1
CONST adSchemaCharacterSets=2
CONST adSchemaCheckConstraints=5
CONST adSchemaCollations=3
CONST adSchemaColumnPrivileges=13
CONST adSchemaColumns=4
CONST adSchemaColumnsDomainUsage=11
CONST adSchemaConstraintColumnUsage=6
CONST adSchemaConstraintTableUsage=7
CONST adSchemaCubes=32
CONST adSchemaDBInfoKeywords=30
CONST adSchemaDBInfoLiterals=31
CONST adSchemaDimensions=33
CONST adSchemaForeignKeys=27
CONST adSchemaHierarchies=34
CONST adSchemaIndexes=12
CONST adSchemaKeyColumnUsage=8
CONST adSchemaLevels=35
CONST adSchemaMeasures=36
CONST adSchemaMembers=38
CONST adSchemaPrimaryKeys=28
CONST adSchemaProcedureColumns=29
CONST adSchemaProcedureParameters=26
CONST adSchemaProcedures=16
CONST adSchemaProperties=37
CONST adSchemaProviderSpecific=-1
CONST adSchemaProviderTypes=22
CONST adSchemaReferentialConstraints=9
CONST adSchemaSchemata=17
CONST adSchemaSQLLanguages=18
CONST adSchemaStatistics=19
CONST adSchemaTableConstraints=10
CONST adSchemaTablePrivileges=14
CONST adSchemaTables=20
CONST adSchemaTranslations=21
CONST adSchemaTrustees=39
CONST adSchemaUsagePrivileges=15
CONST adSchemaViewColumnUsage=24
CONST adSchemaViews=23
CONST adSchemaViewTableUsage=25
CONST adSearchBackward=-1
CONST adSearchForward=1
CONST adSeek=&H00400000
CONST adSeekAfter=&H8
CONST adSeekAfterEQ=&H4
CONST adSeekBefore=&H20
CONST adSeekBeforeEQ=&H10
CONST adSeekFirstEQ=&H1
CONST adSeekLastEQ=&H2
CONST adSimpleRecord=0
CONST adSingle=4
CONST adSmallInt=2
CONST adStateClosed=&H00000000
CONST adStateConnecting=&H00000002
CONST adStateExecuting=&H00000004
CONST adStateFetching=&H00000008
CONST adStateOpen=&H00000001
CONST adStatusCancel=&H0000004
CONST adStatusCantDeny=&H0000003
CONST adStatusErrorsOccurred=&H0000002
CONST adStatusOK=&H0000001
CONST adStatusUnwantedEvent=&H0000005
CONST adStructDoc=2
CONST adTinyInt=16
CONST adTypeBinary=1
CONST adTypeText=2
CONST adUnsignedBigInt=21
CONST adUnsignedInt=19
CONST adUnsignedSmallInt=18
CONST adUnsignedTinyInt=17
CONST adUpdate=&H01008000
CONST adUpdateBatch=&H00010000
CONST adUseClient=3
CONST adUserDefined=132
CONST adUseServer=2
CONST adVarBinary=204
CONST adVarChar=200
CONST adVariant=12
CONST adVarNumeric=139
CONST adVarWChar=202
CONST adWChar=130
CONST adWriteChar=0
CONST adWriteLine=1
CONST adwrnSecurityDialog=&He85
CONST adwrnSecurityDialogHeader=&He86
CONST adXactAbortRetaining=&H00040000
CONST adXactBrowse=&H00000100
CONST adXactChaos=&H00000010
CONST adXactCommitRetaining=&H00020000
CONST adXactCursorStability=&H00001000
CONST adXactIsolated=&H00100000
CONST adXactReadCommitted=&H00001000
CONST adXactReadUncommitted=&H00000100
CONST adXactRepeatableRead=&H00010000
CONST adXactSerializable=&H00100000
CONST adXactUnspecified=&Hffffffff

‘ADC / ADO Constants
CONST adcExecAsync=2
CONST adcExecSync=1
CONST adcFetchAsync=3
CONST adcFetchBackground=2
CONST adcFetchUpFront=1
CONST adcReadyStateComplete=4
CONST adcReadyStateInteractive=3
CONST adcReadyStateLoaded=2

 

5.CDO

‘For SMTP server authentication
Const cdoAnonymous  = 0
Const cdoBasic       = 1
Const cdoNTLM       = 2

‘For SMTP server network option
Const cdoSendUsingPickup = 1
Const cdoSendUsingPort   = 2

Delete large amount of data from a table

$
0
0

刪除大量資料作法

Method 1

若刪除完成之後留下的資料較多的話(例如要刪除1/3的資料),就用WHILE DELETE top語法來刪除

 declare @n int
 while 1=1
 begin
 DELETE top(2000)
 FROM dbo.BigTable
 WHERE time <= '2013-09-03 22:00:00.000'
 OPTION(MAXDOP 1) -- 可考慮是否只使用一個CPU來執行刪除動作
 set @n=@@ROWCOUNT
 if @n<2000
 break
 end

Method 2
若留下的資料比較少(例如要刪除2/3的資料或更多的資料),就可以考慮INSERT INTO再TRUNCATE或INSERT INTO再RENAME

  • INSERT INTO and TRUNCATE

1.將要保留的資料INSERT INTO到dbo.Temp_BigTable

SELECT * INTO dbo.Temp_BigTable
 FROM dbo.Temp_BigTable
 WHERE Date < '2015/1/1';
2.清空dbo.Temp_BigTable
 TRUNCATE TABLE dbo.Temp_BigTable;
3.INSERT INTO dbo.BigTable from dbo.Temp_BigTable
 INSERT INTO dbo.BigTable
 SELECT * FROM dbo.Temp_BigTable;

可以參考這篇 SQL Server: Delete a Huge Amount of Data from a Table

  • INSERT INTO再RENAME

1.將要保留的資料INSERT INTO到dbo.Temp_BigTable
2.DROP TABLE dbo.Temp_BigTable
3.RENAME dbo.Temp_BigTable to dbo.BigTable

注意:
因為原Table會被刪除,所以需事先調查與保存與重新設定以下項目
1.權限
2.Trigger
3.Index

PS.以下狀況無法直接DROP TABLE
1.被Foreign Key或view with SCHEMABINDING reference的資料表
2.複寫發行資料表
3.啟用CDC的資料表

若有view with schemabinding

CREATE VIEW v_Table_2
WITH SCHEMABINDING

DROP TABLE會出現以下錯誤

Msg 3729, Level 16, State 1, Line 2
Cannot DROP TABLE ‘dbo.Table_1’ because it is being referenced by object ‘v_Table_2’.

若有Foreign key reference

DROP TABLE會出現以下錯誤

Msg 3726, Level 16, State 1, Line 2
Could not drop object ‘dbo.Table_1’ because it is referenced by a FOREIGN KEY constraint.

 

Reference:

SQL Server: Delete a Huge Amount of Data from a Table

Visual Studio(SSDT BIDS) for SQL Server

$
0
0

Visual Studio(SSDT BIDS) for SQL Server

SSDT: SQL Server Data Tool

BIDS: Business Intelligence Development Studio

SQL Server Visual Studio Version
SQL Server 2005 透過SQL Server安裝程式勾選安裝

Visual Studio 2005 8.0.50727.42 (RTM.050727-4200)

BIDS_VS2005_v8.0.50727.42

SQL Server 2008 透過SQL Server安裝程式勾選安裝

Visual Studio 2008 9.0.30729.1 SP

Visual Studio 2008含有SP1

Actions that are required before you install SQL Server 2008 on a computer that has Visual Studio 2008 or the prerelease version of SQL Server 2008 installed http://support.microsoft.com/kb/956139/en-us

BIDS_VS2008_v9.0.30729.1

SQL Server 2008 R2 透過SQL Server安裝程式勾選安裝

Visual Studio 2008 9.0.30729.4462 QFE

Visual Studio 2008含有SP1,但是畫面沒有SP字眼

SQL Server Data Tools – 2012 年 12 月版的更新 SQL Server 2008所安裝的Visual Studio 2008含有SP1 http://support.microsoft.com/kb/956139/en-us

BIDS_VS2008_v9.0.30729.4462

SQL Server 2012 Visual Studio 2010 (SQL Server Data Tools) 10.0.40219.1 SP1Rel 含有Visual Studio 2010 SP1

Visual Studio 2010 SSDT的更新 SQL Server Data Tools – 2012 年 12 月版的更新

http://msdn.microsoft.com/zh-tw/data/jj650014

SSDT_VS2010_10.0.40219.1

SQL Server 2014 需自行下載

2014-10-27 Microsoft SQL Server Data Tools – Business Intelligence for Visual Studio 2013 http://www.microsoft.com/zh-tw/download/details.aspx?id=42313

2014-06-26 Microsoft SQL Server Data Tools – Business Intelligence for Visual Studio 2012 http://www.microsoft.com/zh-tw/download/details.aspx?id=36843

 

Download SQL Server Data Tools (SSDT)
https://msdn.microsoft.com/en-us/library/mt204009.aspx

SQL Server Rowset Trace

$
0
0

Rowset trace(Rowset Provider)

Server-Side Trace with file provider(File Provider)
如果是Server-Side Trace則是使用file provider

 select * from sys.traces where is_rowset = 0 and path is not NULL

PS. The file provider is designed with a guarantee that no event data will be lost.

Rowset Trace(Rowset Provider)
SQL Server Profiler連線到SQL Server啟動的就是Rowset Trace (使用rowset provider)

select * from sys.traces where is_rowset = 1 and path is NULL

PS. The rowset provider, on the other hand, is not designed to make any data loss guarantees.
If data is not being consumed quickly enough and its internal buffers fill, it waits up to 20 seconds before it begins jettisoning events in order to free buffers to get things moving. The SQL Server Profiler client tool will send a special error message if events are getting dropped, but you can also find out if you’re headed in that direction by monitoring SQL Server’s TRACEWRITE wait type, which is incremented as threads are waiting for buffers to free up.
SQL Server Profiler pulls these events from the rowset provider via a call to sp_trace_getdata and performs a “pivot” to produce the human-readable output we’re used to seeing. This is yet another reason that the rowset provider can be less efficient than the file provider—sending so many rows can produce a huge amount of network traffic.
If you do require rowset provider-like behavior for your monitoring needs, you luckily will not need to figure out how to manipulate this data. SQL Server 2005 ships with a series of managed classes in the Microsoft.SqlServer.Management.Trace namespace, designed to help with setting up and consuming rowset traces. The use of these classes is beyond the scope of this chapter, but they are well documented in the SQL Server TechCenter on TechNet, and readers should have no trouble figuring out how to exploit what they offer.

Reference:
Server-Side Tracing and Collection
https://msdn.microsoft.com/en-us/library/cc293613.aspx
SQL Trace Architecture and Terminology
https://msdn.microsoft.com/en-us/library/cc293610.aspx
SQL SERVER – Server Side and Client Side Trace
http://blog.sqlauthority.com/2015/12/15/sql-server-server-side-and-client-side-trace/

Configure Performance Log collection for SQL Server Performance Baseline

$
0
0

設定收集效能計數器記錄檔,建立SQL Server效能基準線

1.啟動效能監視器

Perfmon

2.新增收集器

Data Collector Sets>User Defined>New>Data Collector Set

W2K8R2_PerfLog01

3.輸入名稱 (例如 SQLPerfLogBaseline)並選擇 Create from a template (Recommended)

W2K8R2_PerfLog02

4.範本Template,選擇System Performance

W2K8R2_PerfLog03

5.指定blg檔存放的根目錄

W2K8R2_PerfLog04

6.選擇Open Properties for this data collector set

W2K8R2_PerfLog05

7.按下Finish之後,則出現此視窗

W2K8R2_PerfLog06

8.在schedule頁籤,新增一個排程,例如每天08:00啟動

W2K8R2_PerfLog07

9.在Stop Condition頁籤,設定停止條件,例如勾選Overall Duration 16 hours,在Limit限制的區塊,勾選 Restart the data collector set at limits.,勾選 Maximum Size:設定300MB

W2K8R2_PerfLog08

10.按下OK之後,回到主視窗,若不需要可將NT Kernel trace刪除

W2K8R2_PerfLog09

11.在Performance Counter按右鍵選擇 Properties

W2K8R2_PerfLog10

12.修改預設選取的Performance counters,只留下需要的Performance Counter

W2K8R2_PerfLog11

12.修改與確認blg黨與報表檔保留期間

在SQLPerfLogBaseline右鍵選擇Data Manager

W2K8R2_PerfLog12

13.修改限制設定

W2K8R2_PerfLog13

14.在Action頁籤,調整成自己要想要保留的規則,就完成所有設定

W2K8R2_PerfLog14

15.可將目前的設定另存成XML的範本檔template

W2K8R2_PerfLog15_template

W2K8R2_PerfLog16_template

16.時間到了就會自動啟動,也可以手動按右鍵啟動,就會開始收集。

W2K8R2_PerfLog17

Reference:
Creating Data Collector Sets
https://technet.microsoft.com/en-us/library/cc749337(v=ws.11).aspx

Use SQL Server Objects
https://technet.microsoft.com/en-us/library/ms190382.aspx


SQL Server 2008 R2 Performance Dashboard Reports

$
0
0

Microsoft® SQL Server® 2012 Performance Dashboard Reports
https://www.microsoft.com/en-us/download/details.aspx?id=29063

Supported Operating System

Windows 7, Windows Server 2008 R2, Windows Server 2008 Service Pack 2, Windows Vista Service Pack 2

    Works with the following SQL Server versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014

1.安裝

SQL2008R2PerfDashboard00

SQL2008R2PerfDashboard01

SQL2008R2PerfDashboard02

SQL2008R2PerfDashboard03

SQL2008R2PerfDashboard04

SQL2008R2PerfDashboard05

2.設定

Getting Started With the Performance Dashboard Reports
1. In each SQL Server instance, run the script %ProgramFiles(x86)%\Microsoft SQL Server\110\Tools\Performance Dashboard\setup.sql

SQL2008R2PerfDashboard06

2. In the Object Explorer pane in SSMS, right mouse click on the SQL Server instance node, then choose Reports-Custom Reports.  Browse to the installation directory and open the performance_dashboard_main.rdl file.

SQL2008R2PerfDashboard07

SQL2008R2PerfDashboard08

 

SQL2008R2PerfDashboard09

3.使用

安裝完成之後,在上一個步驟按下run,就會開啟Performance Dashboard Reports

SQL2008R2PerfDashboard10

 

SQL Server Performance study resources

$
0
0

SQL Server Performance study resources

查詢處理架構:
Query Processing Architecture
https://technet.microsoft.com/en-us/library/cc280362(v=sql.105).aspx

效能監控與分析:
Monitor and Tune for Performance
https://msdn.microsoft.com/en-us/library/ms189081.aspx

Topic Task
Monitor SQL Server Components Required steps to monitor any SQL Server component.
Performance Monitoring and Tuning Tools Lists the monitoring and tuning tools available with SQL Server.
Establish a Performance Baseline How to establish a performance baseline.
Isolate Performance Problems Isolate database performance problems.
Identify Bottlenecks Monitor and track server performance to identify bottlenecks.
Monitor CPU Usage
Monitor Disk Usage
Monitor Memory Usage
Server Performance and Activity Monitoring Use SQL Server and Windows performance and activity monitoring tools.
Open Activity Monitor (SQL Server Management Studio) 活動監視器
https://msdn.microsoft.com/en-us/library/ms175518.aspx
Microsoft® SQL Server® 2012 Performance Dashboard Reports
https://www.microsoft.com/en-us/download/details.aspx?id=29063
Display and Save Execution Plans Display and save execution plans to a file in XML format.

 

目前正在執行的Query
Determine the Currently Executing Statement in a Long Running SQL Stored Procedure
https://blogs.msdn.microsoft.com/taylaf/2010/01/25/determine-the-currently-executing-statement-in-a-long-running-sql-stored-procedure/

SELECT  requests.session_id,
         requests.status,
         requests.command,
         requests.statement_start_offset,
         requests.statement_end_offset,
         requests.total_elapsed_time,
         details.text
 FROM    sys.dm_exec_requests requests
 CROSS APPLY sys.dm_exec_sql_text (requests.plan_handle) details
 WHERE   requests.session_id > 50
 ORDER BY total_elapsed_time DESC

 

Status:
sys.dm_exec_sessions (Transact-SQL)
https://msdn.microsoft.com/en-us/library/ms176013.aspx
Status of the session. Possible values:
 Running – Currently running one or more requests
 Sleeping – Currently running no requests
 Dormant – Session has been reset because of connection pooling and is now in prelogin state.
 Preconnect – Session is in the Resource Governor classifier.
Is not nullable.

sys.dm_exec_requests (Transact-SQL)
https://msdn.microsoft.com/en-us/library/ms177648.aspx
Status of the request. This can be one of the following:
Background
Running
Runnable
Sleeping
Suspended
Is not nullable.

Different Status of a SPID in SQL Server and What do they mean
https://blogs.msdn.microsoft.com/sqlsakthi/2011/02/08/different-status-of-a-spid-in-sql-server-and-what-do-they-mean/
How It Works: What is a Sleeping / Awaiting Command Session
https://blogs.msdn.microsoft.com/psssql/2008/04/21/how-it-works-what-is-a-sleeping-awaiting-command-session/

Wait Type:
Wait statistics, or please tell me where it hurts
http://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/
Doctor, this SQL Server appears to be sick….
https://blogs.msdn.microsoft.com/psssql/2009/11/24/doctor-this-sql-server-appears-to-be-sick/
Case Study: Part 1: CXPACKET Wait Stats & ‘max degree of parallelism’ Option: Introduction to Using Wait Stats to Identify & Remediate Query Parallelism Bottlenecks
https://blogs.msdn.microsoft.com/jimmymay/2008/11/28/case-study-part-1-cxpacket-wait-stats-max-degree-of-parallelism-option-introduction-to-using-wait-stats-to-identify-remediate-query-parallelism-bottlenecks/
Troubleshooting ASYNC_NETWORK_IO, NETWORKIO
https://blogs.msdn.microsoft.com/joesack/2009/01/08/troubleshooting-async_network_io-networkio/
What is WRITELOG waittype and how to troubleshoot and fix this wait in SQL Server
https://blogs.msdn.microsoft.com/sqlsakthi/2011/04/16/what-is-writelog-waittype-and-how-to-troubleshoot-and-fix-this-wait-in-sql-server/
What’s that HTDELETE wait type?
https://blogs.msdn.microsoft.com/ialonso/2014/07/23/whats-that-htdelete-wait-type/
Meditation on SQL Trace performance Impact and Wait types
https://blogs.msdn.microsoft.com/sqlmeditation/2012/12/12/meditation-on-sql-trace-performance-impact-and-wait-types/
REPL_SCHEMA_ACCESS wait type
https://blogs.msdn.microsoft.com/psssql/2014/06/03/repl_schema_access-wait-type/
sys.dm_os_wait_stats (Transact-SQL)
https://msdn.microsoft.com/en-us/library/ms179984.aspx
The SQL Server Wait Type Repository…
https://blogs.msdn.microsoft.com/psssql/2009/11/02/the-sql-server-wait-type-repository/

透過SQL Profiler trace分析:
Troubleshooting and Analysis with Traces
https://msdn.microsoft.com/en-us/library/cc293616.aspx

Distributed query vs OPENQUERY

$
0
0

Distributed query (Four-part name) and OPENQUERY

OpenQuery Distributed Query
速度 一般來說 OPENQUERY較快一點 也很快
Query optimizer 遠端產生執行計畫 本地產生執行計畫 產生local query與remote query
連線數量 只會產生1條連線到遠端取回資料 會產生2條連線
第1條連線先取回統計資訊
第2條連線再取回資料
優點 可以在一個Query裡面JOIN多個不同SQL Server的Table
可能出現issue 如果太多連線使用Distributed Query,則會造成大量等待SOSHOST_MUTEX wait
缺點 雖然有WHERE條件,但SQL Server可能會送出SELECT * FROM the remote table,然後等資料回到本地端才進行filter
權限 只需要設定SELECT資料表的權限 為了產生最佳執行計畫,remote login account必須有以下權限,才能取得完整的統計資訊,若沒有以下權限,則查詢效能則會比較差 To create the best query plans the user must own the table or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role on the linked server. https://msdn.microsoft.com/en-us/library/ms175537.aspx 但SQL 2012開始則不需要此權限

Best Performer: Distributed query (Four-part) or OPENQUERY when executing linked server queries in SQL Server
https://blogs.msdn.microsoft.com/sqlsakthi/2011/05/08/best-performer-distributed-query-four-part-or-openquery-when-executing-linked-server-queries-in-sql-server/
Security for Linked Servers
http://msdn.microsoft.com/en-us/library/ms175537.aspx
Guidelines for Using Distributed Queries
https://msdn.microsoft.com/en-us/library/ms175129.aspx
OPENQUERY (Transact-SQL)
https://msdn.microsoft.com/en-us/library/ms188427.aspx
Optimizing Distributed Queries
https://technet.microsoft.com/en-us/library/ms180972(v=sql.105).aspx
Improving the Performance of Distributed Queries
http://sqlmag.com/database-performance-tuning/improving-performance-distributed-queries

 

DBA Fundamentals-SQL Server Performance Tuning

$
0
0

2016/9/21 PASS online event
DBA Fundamentals: SQL Server Performance Tuning
Speaker: Pinal Dave

1.資料庫相容性層級影響基數估計(Cardinality Estimation)
提升資料庫相容性層級就可以改善效能

The New and Improved Cardinality Estimator in SQL Server 2014
https://blogs.technet.microsoft.com/dataplatforminsider/2014/03/17/the-new-and-improved-cardinality-estimator-in-sql-server-2014/
Cardinality Estimation (SQL Server)
https://msdn.microsoft.com/en-us/library/dn600374.aspx
CE(Cardinality Estimation)會預測您的查詢可能傳回的資料列數目。 查詢最佳化工具使用基數預測,來產生最佳查詢計劃。 CE 愈精確,查詢計劃通常愈理想。
In 1998, a major update of the CE was part of Microsoft SQL Server 7.0, for which the compatibility level was 70. Subsequent updates came with SQL Server 2014 and SQL Server 2016, meaning compatibility levels 120 and 130. The CE updates for levels 120 and 130 incorporate assumptions and algorithms that work well on modern data warehousing workloads and on OLTP (online transaction processing).
新版(層級 120 和 130 )的基數估計更新了合併假設與演算法,增強並適用於新式資料倉儲工作負載和 OLTP (線上交易處理)。

改善了以下的問題
Your application system could possibly have an important query whose plan is changed to a slower plan due to the new CE. Such a query might be like one of the following:

  • An OLTP query that runs so frequently that multiple instance of it often run concurrently.
  • A SELECT with substantial aggregation that runs during your OLTP business hours.

Troubleshooting Poor Query Performance: Cardinality Estimation
https://technet.microsoft.com/en-us/library/ms181034(v=sql.105).aspx

2.自動更新與建立統計資訊
Statistics
https://msdn.microsoft.com/en-us/library/ms190397.aspx

3.Missing index (script from Pinal Dave blog)

http://blog.sqlauthority.com
http://go.sqlauthority.com

SQL SERVER – Missing Index Script – Download


4.Wait Stats and Queues (script from Pinal Dave blog)

http://blog.sqlauthority.com

http://go.sqlauthority.com

http://blog.sqlauthority.com/2016/09/17/sql-server-2016-wait-stats-queues-script-updated-identify-resource-bottlenecks/

 

add text to beginning or end of each line using SSMS

$
0
0

1.Add text to the beginning of each line

Ctrl+H

type “^” in the “Find”

type text you want to add in “Replace with”

Choose the “Regular expressions” checkbox

replace_add_ the beginning of each line1

replace_add_ the beginning of each line2

 

2.Add text to the end of each line

Ctrl+H

type “$” in the “Find”

type text you want to add in “Replace with”

Choose the “Regular expressions” checkbox

replace_add_ the end of each line1

replace_add_ the end of each line2

Database Corruption Challenge – Steve Stedman

$
0
0

2016年9月13日 PASS
Database Corruption Challenge – Steve Stedman
Presented by Steve Stedman
https://www.youtube.com/watch?v=5oBA5nL0uRc&feature=youtu.be&a

1.備份資料庫,還原至測試機來進行修復工作(確保還原程序遭遇問題時,可以重頭再來修復一次)
2.如果決定用allow data loss,嘗試先找出可能遺失的資料並事先嘗試SELECT INTO保留下來
3.執行之前尋求是否有其他人的意見

 

定期執行

osql -E -Q"DBCC CHECKDB (AdventureWorks) WITH ALL_ERRORMSGS, NO_INFOMSGS" -oC:\outputfile.txt
sqlcmd -E -Q"DBCC CHECKDB (AdventureWorks) WITH ALL_ERRORMSGS, NO_INFOMSGS" -o C:\outputfile.txt

 

PS.WITH NO_INFOMSGS只顯示錯誤訊息,一般的information不顯示

 

基本流程

1.將有損毀的資料庫備份檔還原到測試機,切換成single_user mode。

ATLER DATABASE AdventureWorks SET SINGLE_USER WITH ROLLBACK_IMMEDIATELY;

2.取得錯誤訊

USE [master];
GO
DBCC CHECKDB (AdventureWorks) WITH NO_INFOMSGS;
GO

DBCC CHECKTABLE ('HumanResources.Employee') WITH NO_INFOMSGS;
GO

2.取回損毀的資料

(1)如果原資料表還能查詢的狀況

A.透過DBCC CHECKTABLE找出哪一筆或哪幾筆資料損毀

page(1, 280) ->page 280

DBCC TRACEON(3604)
DBCC PAGE(dbname, 1, 280,2) with no_infomsgs;
從結果找出m_type
m_type=1 ->data page
slotcount =27 -> number of rows in this page
所以如果執行allow data loss則會出現27然後修復完成(損毀的地方)

B.透過select with non-clustered Index取回一些資料。

select col1, col2 from table with (index=clusted_index1);

利用彙總函數,比對clustered index與non-clustered index資料是否有不同

PS.數值與日期欄位可用SUM(column),文字欄位可用 SUM(LEN(column))

若查出來值不同(例如col4不同),表示其中一個欄位有損毀

使用OUTER ALL JOIN 同一個TABLE 找出哪一筆的col4是NULL

 

因無法直接update or delete那一筆損毀的資料,若執行會出現錯誤

所以從non-cluster index SELECT資料到table_save暫存資料表

 

D.嘗試修復

DBCC CHECKTABLE(tableName, REPAIR_REBUILD)

通常無法修復

DBCC CHECKTABLE(tableName, REPAIR_ALLOW_DATA_LOSS)

出現找到錯誤,並已經修復
但執行select * from table發現只剩一半的資料,其他消失

E.將資料從table_save補回原資料表

接下就INSERT table select * from table_save
where table.id not in (select id from table)

 

(2)如果原資料表不能查詢的狀況

A.先透過select with non-clustered Index取回一些資料。(如果後面的步驟無法取得完整資料,最少還有這些)

B.嘗試透過DBCC IND, DBCC PAGE來取回損毀資料表(clustered index)的完整資料

C.再用TRUNCATE TABLE來移除損毀

D.INSERT SELECT from救回資料的資料表

3.修復資料庫並回存資料

truncate table Table_1
insert into Table_1 select * from Table_copy

File xxx.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see get-help about_signing

$
0
0

PS C:\Temp>.\myPS.ps1

C:\Temp\myPS.ps1 檔案無法載入,因為這個系統上已停用指令碼執行。如需詳細資訊,請參閱 “get-help about_signing”。
位於 行:x 字元:xx
+ .\myPS.ps1 <<<<
+ CategoryInfo          : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException

File C:\Temp\myPS.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.

Resolution:

PS C:\Users\Administrator>Set-ExecutionPolicy RemoteSigned

Using the Set-ExecutionPolicy Cmdlet
https://technet.microsoft.com/en-us/library/ee176961.aspx

  • Restricted – No scripts can be run. Windows PowerShell can be used only in interactive mode.
  • AllSigned – Only scripts signed by a trusted publisher can be run.
  • RemoteSigned – Downloaded scripts must be signed by a trusted publisher before they can be run.
  • Unrestricted – No restrictions; all Windows PowerShell scripts can be run.

Set-ExecutionPolicy
https://technet.microsoft.com/en-us/library/hh849812.aspx


SQL Server Learning Resource

$
0
0

SQL Server 學習資源


中英文官方線上課程
Microsoft Virtual Academy
Database Development Course
https://mva.microsoft.com/training-topics/database-development#!jobf=Developer&lang=1033

必學的 SQL Server 2014 資料庫管理技巧
https://mva.microsoft.com/zh-tw/training-courses/-sql-server-2014–11125
SQL Server 管理入門 (一):安裝、設定與連線
https://mva.microsoft.com/zh-tw/training-courses/sql-server–11718?l=Pym6n7iEB_9804984382

SQLPASS
http://www.sqlpass.org/
線上研討會

研討會錄影檔會放到youtube
High Availabilty Disaster Recovery Virtual Chapter
https://www.youtube.com/channel/UCVXM_bmBuTEln3K4GHeuBAQ
SQLPASS Taiwan
https://www.facebook.com/groups/sqlpasstaiwan/
每個月舉辦研討會

Super SQL Server
https://www.facebook.com/groups/222546864546011/
不定期舉辦線上研討會課程
Tutorials
SQL Server 2008 R2
https://msdn.microsoft.com/en-us/library/ms167593(v=sql.105).aspx

SQL Server技術文件
SQL Server 2008 R2 – 2016 Technical Documentation
https://msdn.microsoft.com/zh-tw/library/ms130214.aspx

微軟虛擬實驗室
https://www.microsoft.com/en-us/cloud-platform/virtual-labs
線上操作練習

微軟官方
Microsoft Ignite
https://www.youtube.com/channel/UCrhJmfAGQ5K81XQ8_od1iTg
新技術
微軟官方影片
Channel 9 是一個社群。在此社群中,產品幕後推手有機會現身,親自與產品使用者交流。
https://channel9.msdn.com/
Azure, BigData相關

 

好書推薦:
SQL Server 2012管理實戰
http://www.delightpress.com.tw/book.aspx?book_id=skud00023
分類| 資料庫
原文書名|
作者| 洪玉茹  恆逸資訊  陳俊宇  日盛金控  劉承修
譯者|
校閱者| 胡百敬
出版日期| 2012-05-10

SQL Server Performance Tuning 效能調校
http://www.delightpress.com.tw/book.aspx?book_id=SKUD00026
分類| 資料庫
原文書名|
作者| 胡百敬‧姚巧玫‧周妙謙  日盛金控  劉承修
譯者|
校閱者|
出版日期| 2014-06-06

 

Training Kit (Exam 70-462) Administering Microsoft SQL Server 2012 Databases (MCSA)
https://www.microsoftpressstore.com/store/training-kit-exam-70-462-administering-microsoft-sql-9780735666061
Training Kit (Exam 70-461) Querying Microsoft SQL Server 2012 (MCSA)
https://www.microsoftpressstore.com/store/training-kit-exam-70-461-querying-microsoft-sql-server-9780735666047
Training Kit (Exam 70-463) Implementing a Data Warehouse with Microsoft SQL Server 2012 (MCSA)
https://www.microsoftpressstore.com/store/training-kit-exam-70-463-implementing-a-data-warehouse-9780735666092

 

Log Shipping Monitoring and Troubleshooting

$
0
0

Log Shipping Monitoring and Troubleshooting
交易紀錄傳送監控與疑難排解


1.Log Shipping status
View the Log Shipping Report (SQL Server Management Studio)
https://msdn.microsoft.com/en-us/library/ms181149.aspx

To display the Transaction Log Shipping Status report on a server instance

  1. Connect to a monitor server, primary server, or secondary server.
  2. Right-click the server instance in Object Explorer, point to Reports, and point to Standard Reports.
  3. Click Transaction Log Shipping Status.

sp_help_log_shipping_monitor (Transact-SQL)
https://msdn.microsoft.com/en-us/library/ms187820.aspx

sp_help_log_shipping_monitor

Remarks
sp_help_log_shipping_monitor must be run from the master database on the monitor server.

Permissions
Requires membership in the sysadmin fixed server role.

找出Monitoring Server方法

SELECT monitor_server FROM msdb.dbo.log_shipping_primary_databases;

or

SELECT monitor_server FROM msdb.dbo.log_shipping_secondary;

 

2.Job History

View the Job History
https://msdn.microsoft.com/en-us/library/ms181046.aspx

     To view the job history log

  1. In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.
  2. Expand SQL Server Agent, and then expand Jobs.
  3. Right-click a job, and then click View History.
  4. In the Log File Viewer, view the job history.
  5. To update the job history, click Refresh. To view fewer rows, click the Filter button and enter filter parameters.

or

-- lists all job information for the NightlyBackups job. 
USE msdb ; 
GO 

EXEC dbo.sp_help_jobhistory  
    @job_name = N'NightlyBackups' ; 
GO

 

3.Backup and Restore History
Backup History and Header Information (SQL Server)
https://msdn.microsoft.com/en-us/library/ms188653.aspx

Query SQL Server backup history and restore history records
https://blogs.msdn.microsoft.com/bradchen/2014/03/12/query-sql-server-backup-history-and-restore-history-records/
4.ERRORLOG
View the SQL Server Error Log (SQL Server Management Studio)
https://msdn.microsoft.com/en-us/library/ms187109.aspx

  1. In Object Explorer, connect to an instance of the SQL Server and then expand that instance.
  2. Find and expand the Management section (Assuming you have permissions to see it).
  3. Right-click on SQL Server Logs, select View, and choose View SQL Server Log.

5.Event log
Start Event Viewer
https://technet.microsoft.com/en-us/library/cc766401(v=ws.11).aspx

To start Event Viewer by using the Windows interface

  1. Click the Start button.
  2. Click Control Panel .
  3. Click System and Maintenance .
  4. Click Administrative Tools .
  5. Double-click Event Viewer .

To start Event Viewer by using a command line

  1. Open a command prompt. To open a command prompt, click Start , click All Programs , click Accessories and then click Command Prompt .
  2. Type eventvwr .

Reference:
Monitor Log Shipping (Transact-SQL)
https://msdn.microsoft.com/en-us/library/ms190224.aspx

Stored procedure Description Run this procedure on
sp_help_log_shipping_monitor_primary Returns monitor records for the specified primary database from the log_shipping_monitor_primary table. Monitor server or primary server
sp_help_log_shipping_monitor_secondary Returns monitor records for the specified secondary database from the log_shipping_monitor_secondary table. Monitor server or secondary server
sp_help_log_shipping_alert_job Returns the job ID of the alert job. Monitor server, or primary or secondary server if no monitor is defined
sp_help_log_shipping_primary_database Retrieves primary database settings and displays the values from the log_shipping_primary_databases and log_shipping_monitor_primary tables. Primary server
sp_help_log_shipping_primary_secondary Retrieves secondary database names for a primary database. Primary server
sp_help_log_shipping_secondary_database Retrieves secondary-database settings from the log_shipping_secondary, log_shipping_secondary_databases and log_shipping_monitor_secondary tables. Secondary server
sp_help_log_shipping_secondary_primary (Transact-SQL) This stored procedure retrieves the settings for a given primary database on the secondary server. Secondary server

 

Adding a log shipping monitor
http://www.sqlservercentral.com/articles/Log+Shipping/77295/

 

SQL Server Physical Joins

$
0
0

SQL Server Physical Join (Nested Loops joins, Merge joins, Hash joins)


Advanced Query Tuning Concepts
https://technet.microsoft.com/en-us/library/ms191426(v=sql.105).aspx

SQL Server employs three types of join operations:

  • Nested loops joins
  • Merge joins
  • Hash joins

 

Nest Loops Joins

If one join input is small (fewer than 10 rows) and the other join input is fairly large and indexed on its join columns, an index nested loops join is the fastest join operation because they require the least I/O and the fewest comparisons. For more information about nested loops, see Understanding Nested Loops Joins.

Nested Loops Join
https://blogs.msdn.microsoft.com/craigfr/2006/07/26/nested-loops-join/
OPTIMIZED Nested Loops Joins
https://blogs.msdn.microsoft.com/craigfr/2009/03/18/optimized-nested-loops-joins/

Merge Joins

If the two join inputs are not small but are sorted on their join column (for example, if they were obtained by scanning sorted indexes), a merge join is the fastest join operation. If both join inputs are large and the two inputs are of similar sizes, a merge join with prior sorting and a hash join offer similar performance. However, hash join operations are often much faster if the two input sizes differ significantly from each other. For more information, see Understanding Merge Joins.

Merge Join
https://blogs.msdn.microsoft.com/craigfr/2006/08/03/merge-join/

Hash Joins

Hash joins can efficiently process large, unsorted, nonindexed inputs. They are useful for intermediate results in complex queries because:

  • Intermediate results are not indexed (unless explicitly saved to disk and then indexed) and often are not suitably sorted for the next operation in the query plan.
  • Query optimizers estimate only intermediate result sizes. Because estimates can be very inaccurate for complex queries, algorithms to process intermediate results not only must be efficient, but also must degrade gracefully if an intermediate result turns out to be much larger than anticipated.

The hash join allows reductions in the use of denormalization. Denormalization is typically used to achieve better performance by reducing join operations, in spite of the dangers of redundancy, such as inconsistent updates. Hash joins reduce the need to denormalize. Hash joins allow vertical partitioning (representing groups of columns from a single table in separate files or indexes) to become a viable option for physical database design. For more information, see Understanding Hash Joins.

Hash Join

Hash Join

SQL Server Management Studio Keyboard Shortcuts

$
0
0

SQL Server Management Studio Keyboard Shortcuts

常用快速鍵


SQL Server Management Studio Keyboard Shortcuts
https://msdn.microsoft.com/en-us/library/ms174205.aspx

Action SQL Server 2016 SQL Server 2008 R2
Select text from the cursor to the beginning of the document CTRL+SHIFT+ HOME CTRL+SHIFT+ HOME
Select text from the cursor to the end of the document CTRL+SHIFT+END CTRL+SHIFT+END
Select text from the cursor to the start of the current line SHIFT+HOME SHIFT+HOME
Display the Go To Line dialog box CTRL+G CTRL+G
Display the Navigate To dialog box. CTRL+PLUS SIGN (+) No equivalent
Increase line indent TAB TAB
Decrease line indent SHIFT+TAB SHIFT+TAB
Make the selected text upper case CTRL+SHIFT+U CTRL+SHIFT+U
Make the selected text lower case CTRL+U CTRL+SHIFT+L
Make the selected text a comment CTRL+K, CTRL+C CTRL+K, CTRL+C
Uncomment the selected text CTRL+K, CTRL + U CTRL+K, CTRL + U
Run the sp_help system stored procedure ALT+F1 ALT+F1
Run the sp_who system stored procedure CTRL+1 CTRL+1
Run the sp_lock system stored procedure CTRL+2 CTRL+2
Run the stored procedure configured for this shortcut in the Tools, Options, Keyboard, Query Shortcuts dialog CTRL+3 CTRL+3
Run the stored procedure configured for this shortcut in the Tools, Options, Keyboard, Query Shortcuts dialog CTRL+4 CTRL+4

SQL Snippets for SSMS 2008 R2

SSMS Tools Pack

 

How to reset forgotten sa password

$
0
0

How to reset forgotten sa password

如何重設sa密碼  或 忘記sa密碼的情況下加入一個SQL管理員帳戶


如果忘記sa密碼,有2個方法解決

方法一

不需要重啟SQL Server服務,但Login裡面必須要原本就有NT AUTHORITY\SYSTEM帳戶,且此帳戶要有sysadmin Role

1.下載Sysinternals的psexec.exe工具

https://technet.microsoft.com/en-us/sysinternals/bb897553.aspx

2.啟動命令提示字元,用psexec.exe來啟動SSMS,就可以用NT SERVICE\SYSTEM身分Windows驗證登入

PsExec.exe -s -i "C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe"

SQL Server Managment Studio default locations

方法二

處理過程會有downtime,因為需重新啟動SQL Server服務。

1.停止SQL Server服務

2.啟動第1個命令提示字元,以Single user mode啟動SQL Server

Start the SQL Server instance using single user mode (or minimal configuration which will also put SQL Server in single user mode)

SQLServr.Exe –m (or SQLServr.exe –f)

for exsample:

3.在SQL Server本機,啟動第2個命令提示字元,使用sqlcmd用Windows驗證直接登入

SQLCMD –S <Server_Name\Instance_Name>

4.建立一個新Login並給予sysadmin role

create a new account or add an existing login to SYSADMIN server role

CREATE LOGIN [dbasa] with
PASSWORD= N'dbasa_P@ssw0rd',
CHECK_POLICY = OFF
GO
sp_addsrvrolemember 'dbasa', 'SYSADMIN'
GO

5.使用Ctrl+C來第1個命令提示字元的sql server

6.正常啟動SQL Server,就可以用剛剛建立的dbasa管理員帳戶登入,接下來如果需要,就去改掉sa密碼。

 

Reference:

Tips & Tricks: YOU HAVE LOST ACCESS TO SQL SERVER. NOW WHAT?
https://blogs.technet.microsoft.com/sqlman/2011/06/14/tips-tricks-you-have-lost-access-to-sql-server-now-what/

How to verify and change the system administrator password in MSDE or SQL Server 2005 Express Edition
https://support.microsoft.com/en-us/help/322336/how-to-verify-and-change-the-system-administrator-password-in-msde-or-sql-server-2005-express-edition

CREATE LOGIN (Transact-SQL)
https://docs.microsoft.com/en-us/sql/t-sql/statements/create-login-transact-sql

Viewing all 62 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>