Mostrando postagens com marcador SQL Server. Mostrar todas as postagens
Mostrando postagens com marcador SQL Server. Mostrar todas as postagens

How to take SQL server database backup without data?

How to take SQL server database backup without data?

Version: Sql server 2012

There are different method available to achieve this goal. Such as..Script out the source database and then run the script against an empty target database to create all database objects that are in the source database

Right click on the database -> select "tasks" -> "Generate scripts"-> Next -> Select script entire database and all database objects -> Save the sql file in location ->Next-> Next-> Finish.
Now If you want to restore the database just execute  the content of sql file and this will create a new database with only data structure .

This is the content of sql file.

USE [master]
GO
/****** Object:  Database [newdb]    Script Date: 2/3/2017 10:20:17 AM ******/
CREATE DATABASE [newdb]
 CONTAINMENT = NONE
 ON  PRIMARY
( NAME = N'sourcedb', FILENAME = N'E:\MSSQLSERVER\MSSQL11.MSSQLSERVER\MSSQL\DATA\newdb.mdf' , SIZE = 3136KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON
( NAME = N'sourcedb_log', FILENAME = N'E:\MSSQLSERVER\MSSQL11.MSSQLSERVER\MSSQL\DATA\newdb_log.ldf' , SIZE = 768KB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
GO
ALTER DATABASE [newdb] SET COMPATIBILITY_LEVEL = 110
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [newdb].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [newdb] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [newdb] SET ANSI_NULLS OFF
GO
ALTER DATABASE [newdb] SET ANSI_PADDING OFF
GO
ALTER DATABASE [newdb] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [newdb] SET ARITHABORT OFF
GO
ALTER DATABASE [newdb] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [newdb] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [newdb] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [newdb] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [newdb] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [newdb] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [newdb] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [newdb] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [newdb] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [newdb] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [newdb] SET  DISABLE_BROKER
GO
ALTER DATABASE [newdb] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [newdb] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [newdb] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [newdb] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [newdb] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [newdb] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [newdb] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [newdb] SET RECOVERY FULL
GO
ALTER DATABASE [newdb] SET  MULTI_USER
GO
ALTER DATABASE [newdb] SET PAGE_VERIFY CHECKSUM 
GO
ALTER DATABASE [newdb] SET DB_CHAINING OFF
GO
ALTER DATABASE [newdb] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
GO
ALTER DATABASE [newdb] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
EXEC sys.sp_db_vardecimal_storage_format N'newdb', N'ON'
GO
USE [newdb]
GO
/****** Object:  User [test1]    Script Date: 2/3/2017 10:20:17 AM ******/
CREATE USER [test1] FOR LOGIN [test1] WITH DEFAULT_SCHEMA=[dbo]
GO
/****** Object:  User [som]    Script Date: 2/3/2017 10:20:17 AM ******/
CREATE USER [som] FOR LOGIN [som] WITH DEFAULT_SCHEMA=[dbo]
GO
/****** Object:  User [readonly]    Script Date: 2/3/2017 10:20:17 AM ******/
CREATE USER [readonly] FOR LOGIN [readonly] WITH DEFAULT_SCHEMA=[db_datareader]
GO
ALTER ROLE [db_owner] ADD MEMBER [test1]
GO
ALTER ROLE [db_owner] ADD MEMBER [som]
GO
ALTER ROLE [db_datareader] ADD MEMBER [readonly]
GO
/****** Object:  Table [dbo].[Employee]    Script Date: 2/3/2017 10:20:17 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
            [ID] [int] NULL,
            [Value] [varchar](10) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[t1]    Script Date: 2/3/2017 10:20:17 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[t1](
            [id] [varchar](255) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[t2]    Script Date: 2/3/2017 10:20:17 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[t2](
            [id] [varchar](255) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
USE [master]
GO
ALTER DATABASE [newdb] SET  READ_WRITE
GO



Incase if you want to restore the database with different name then we would require to modify the sql file with the new database name .

 Another method is: Backup the source database and restore to the destination database and then delete all table data.

Now we will show you another method which also serve our purpose.

Backup the database without data.

In the SSMS Object Explorer Window, right click on the "newdb" database and choose "Tasks" > "Extract Data-tier Application..."




The [Extract Data-tier Application] wizard will start. 





Provide the DAC package file location 





click "Next"






click "Next"




Now we have newdb.dacpac file generated.


Restore a SQL Server Database from a DAC package

The DAC package can be restored to a target SQL Server instance whose version is equal to or higher than that of the source SQL Server instance.
 SSMS Window, right click [Databases] , and choose "Deploy Data-tier Application...", as shown below

The [Deploy Data-tier Application] wizard will start, Click next in the first [Introduction] screen, and in the [Select Package] screen, click the Browse button to find the DAC package file location


The [Deploy Data-tier Application] wizard will start, Click next and Browse button to find the DAC package file location.





Click Next, and in the [Update Configuration] screen, input the required destination database name or leave it as if you don’t want to change the db name.




That’s it. We have successfully restored the database with only data structure.










    How to create linked server in SQL Server using TSQL ?

    What is linked server?
    Linked Servers allows you to connect to other database instances on the same server or on another machine or remote servers.
    It allows SQL Server to execute SQL scripts against OLE DB data sources on remote servers using OLE DB providers.
    The remote servers can be SQL Server, Oracle, Mysql etc. which means those databases that support OLE DB can be used for linking servers.

    First create a user in mysql which will have permission for atleast select command.

    In mysql Server:-
    mysql> grant select ON `koopkrachtdb `.* TO 'koopreport'@'192.168.2.100' identified by 'Rghdwf4324Fvxg';
    Query OK, 0 rows affected (0.00 sec)



    In SQL Server:-
    Change the fields accordingly to your server settings.



    /****** Object:  LinkedServer [KOOPKRATCHMYSQL]    Script Date: 11/04/2016 08:13:54 ******/
    EXEC master.dbo.sp_addlinkedserver @server = N'KOOPKRATCHMYSQL', @srvproduct=N'MySQL', @provider=N'MSDASQL', @provstr=N'DRIVER={MySQL ODBC 5.3 ANSI Driver}; SERVER=52.71.55.125;DATABASE=koopkrachtdb; USER=koopreport; PASSWORD=Rghdwf4324Fvxg;option=3'
     /* For security reasons the linked server remote logins password is changed with ######## */
    EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'KOOPKRATCHMYSQL',@useself=N'True',@locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL

    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'collation compatible', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'data access', @optvalue=N'true'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'dist', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'pub', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'rpc', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'rpc out', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'sub', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'connect timeout', @optvalue=N'0'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'collation name', @optvalue=null
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'lazy schema validation', @optvalue=N'false'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'query timeout', @optvalue=N'0'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'use remote collation', @optvalue=N'true'
    GO

    EXEC master.dbo.sp_serveroption @server=N'KOOPKRATCHMYSQL', @optname=N'remote proc transaction promotion', @optvalue=N'true'
    GO


    Restore SQL Server MDF Database File Without LDF File

    SQL Server is a relational database management system designed for large-scale transactions, e-commerce applications, data mining, and so on. Moreover, it is widely used on Business platforms for data analysis, data integration and processing components as it keeps all records fast, flexible and secure. The SQL server database contains three files i.e.

    • Primary Database File (MDF file)
    • Secondary Database File (NDF file)
    • Log file (LDF file)

    First, database file is Primary File amongst the three, which consists all the data and schema and also has the file format as .mdf. The second data file is Log File that maintains all the database transactions logs so the desired information can be accessed later to recover SQL server database. There must exist a single log file for each database and it is possible that many log files can be created for an individual database. The file extension for saving the transaction log is .ldf format.

    Why to Restore MDF File Without Log file

    If there is any corruption happens in LDF file, users unable to take the backup of Log file. According to this case, users need to restore SQL Server database without LDF file and need to recreate the Log file as well.

    Solutions to Recover SQL database from MDF file

    There are two methods to restore .mdf database file without .ldf file those are mentioned below:

    • Using SQL Server Management Studio
    • Using Transaction-SQL Script

    By Utilizing SQL Server Management Studio (SSMS)

    Take a look at the steps mentioned below to restore the SQL .mdf file without Log file:

    • First of all, open SQL Server Management Studio.
    • Then, right-click on the databases > click on Attach from the drop-down list.
    • Now, click on Add button > browse the location of database file (MDF) file > choose the file and click on OK button.
    • Finally, display the details in attach dialog box and select LDf file and press Remove button. After that, click on OK button for restoring the MDF file without LDF file. During the restoration of database, SQL server will create a new Log file.
    • At last, check the database in desired databases folder.

    By Utilizing Transact-SQL Script

    Restore SQL Server MDF file without LDF file using Transact SQL script:

    • Click on “New Query” from the Server Management Studio toolbar
    • Execute the following query

    CREATE DATABASE DatabaseName ON
    (FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\DatabaseName.mdf')
    FOR ATTACH_REBUILD_LOG
    GO

    Conclusion

    Here, we end up with the procedure to restore SQL Server database from MDF file only (without LDF file) using SQL Server Management Studio and Transact-SQL script.

    SQL Server Warning Fatal Error 7105: Reasons And Solutions

    MS SQL Server supports Large Object (LOB) data types for storing a large amount of data. Such data types includes Binary LOB (BLOB), Character LOB (CLOB) and Double-byte Character LOB (DBCCLOB) as well. They use a unique structure which is distinct from normal data types. In certain situations, Microsoft SQL server unable to access LOB data that is provided by database page. Users will receive SQL error 7105 while accessing these type of data and the process terminates. It creates critical situations and data loss necessitates MS SQL repairs to be sorted out.

    Consequences of SQL Server Error 7105

    Users may get “MSG 7105” when LOB referenced through the SQL database page row may not be accessed. At this end, SQL server application encounters an error message, which resembles the following as:

    Because of the high severity of errors, SQL server ends the connection. The same error message appears in Windows Application Event Log and SQL ERRORLOG with EventID.

    Causes Behind Error 7105 in SQL Server

    There are following reasons those are mentioned below:

    • The corruption problem may occurs inside the LOB page structure that is given by the database.
    • The query that is failed with NOLOCK or READ UNCOMMITTED ISOLATION query hint.
    • Most probably the error is coming inside the SQL Server Engine leading to the failure of the database query.

    Solutions to Resolve Error Message

    Hence, the following workarounds are discussed as a solution for the respective error:

    • Run DBCC CHECKDB on the SQL Server database
    • It is an inbuilt utility that must be executed to restore or repair the SQL Server database file. Still, in the beginning, it must be run without any repair clause thus, to verify the damage level. After that run DBCC CHECKDB with recommended repair clause to fix SQL Server fatal error 7105. It it possible then, it can fix the error but the problem is that it justifies the data loss which is not suitable.

    • Restore from backup file
    • If the above mentioned method is unable to resolve the error, then users must use the different solution to eliminate the issues. Hence, if a clean and healthy backup is available then, restore the database from backup file for regaining the availability of the data items which is stored in SQL database. It must be possible, only if the backup is available. The steps for restoring procedure are mentioned below:

      • Restore the selected database by clicking on database >> Tasks >> Restore >> Database.
      • After that, select the backup file and then, click OK button.
      • Now, the screen will display the Execution Process and you will have to wait for some time until the process has been completed.
      • After finishing the execution process, a restore database message will be shown on the screen successfully. Click on OK.

    Performing above manual steps, users will be able to restore SQL server database. But if the backup is not available then users can go for third party solution to fix SQL fatal error 7105.

    Effortless Solution to Resolve SQL Server Error 7105

    The most suitable solution for fixing this error code is MS SQL data recovery. It is safe and secure style to troubleshoot the error with the help of below steps:

    Step1: First, launch the software, select the MDF file and then, press Open option.

    Step 2: Once the files are added, the application will Preview the complete recovered database of MDF and NDF files like tables, stored procedures, triggers, and views and so on.

    Step 3: Finally, select an option between two i.e., SQL Server Database and SQL Server Compatible Scripts to export/save the database.

    In the end, a user will be able to get database file without SQL error 7105.

    Conclusion

    While working, various server errors may occur which creates obstacle while accessing the SQL Server database. However, error 7105 in SQL Server is faced due to inaccessibility of large object data that was referenced by a database. We have covered a best possible solution which helps to overcome this issue. Initially, it is suggested to restore the backup of the SQL database, if a user is already having it. Meanwhile, a user can go for another solutions to resolve SQL server 7105.

    Know How To Resolve SQL Server Error 3271?

    When a user is backing up a database or restoration procedure is in process, most of the SQL users faces an error i.e. SQL error 3271. This a type of error encounters when a system is performing an I/O operation.

    The main reason behind this error message is related to I/O operation that displays a message of nonrecoverable I/O error. Therefore, in this article, we have discussed the all the major causes of occurrence of this error and what all are the possible solution to fix this error.

    Causes of Microsoft SQL Server Error 3271

    There are various major causes that are responsible for this error. Therefore, in this section, all the major reasons of occurrence of this error are discussed:

    • Lack of Storage Space
    • The error occurs mainly because of unavailability of space in the storage media. Therefore, it is impossible to fit backup created on the disk. This error message also has some additional text that determines the storage device memory is full, which leads to this I/O error like:

      “A nonrecoverable I/O error occurred on file ‘%ab:’ %ab”

    • VSS Writer of SQL Server
    • The another major reason of the error is an issue with VSS. Volume Shadow Copy Snapshot (VSS) is a replica that is backed up via Window server. Therefore, it can also be possible that an error encountered due to any of the VSS writer that results in failure of the backup operation and further leads to entire backup process failure. Moreover, any error any problem, which is created by VSS writer results an SQL server error 3271.

    • SQL Database Corruption
    • One of the reasons that cause the error is corruption in the SQL database for which user was trying to create a backup. If the user tries to backup the corrupted SQL database then it is more likely to be possible that an I/O error occurs that further leads to error 3271.

    A user must run a check through the SQL error logs to determine the exact reason of the error. After identifying the exact reason, a correct measure or solution can be used to fix the error message and prevent the SQL database from this error in future.

    How To Fix SQL Server Error 3271?

    If the reason of the error message is one of the above mentioned, then a user must follow the measures discussed below:

    • Increase Space On Disk
      1. If the reason of the error is a lack of storage space, then first, a user needs to check the amount of storage space available on the disk on which backup needs to be created.
      2. If there is no space available, first a user needs to free up some space on the storage disk or can use some external storage to save the created backup.
    • Resolve VSS Writer Issue
      1. If the reason of Microsoft SQL error 3271 is VSS writer then, a user must review the instances by running the SQL instance check because the error is due to problematic SQL instance that prevents from taking a snapshot of the database.
      2. After identifying the instance, a user needs to stop that instance and run the backup process without that instance.
      3. If the backup process is completed successfully then it is clear that this particular instance is responsible the error. A user can again check SQL error log to determines the reason behind the inappropriate functionality of that particular instance.
      4. If the user is not able to identify the instance that causing problem on a server, then one needs to stop all the instances on the server to run the backup process.

    Note: When you stop all the available instances then, always keep in mind SQL VSS writer is not in use while taking backup.

    With the help of these above mentioned manual procedures, a user is able to avoid and fix the error and run the backup process successfully.

    Conclusion

    While taking backup of SQL database, a user faces an I/O error generally known as Microsoft SQL Server error 3271. Therefore, all the causes of this error need to determined first, then depending upon the cause of error a respective measure should be taken to resolve it. Hence, in this post manual solutions to resolve these issues are discussed with respect to the cause of the error that a user can use to overcome this issue. However, if the error message occurs while restoring backup then there may be possibility of backup file corruption. In such situation you can take the help of third party SQL backup recovery tool to repair corrupt SQL backup file and fix the error message.

    Steps to Rename Physical Database Files in SQL Server

    The users can manually rename the physical files according to choice using the Transact-SQL commands in the following manner:

    Firstly, we will create a database “new_db” using SQL query. Naturally, the physical files will be named as “new_db.mdf”. Our main aim is to rename SQL Server physical files from “new_db.mdf” to “old_db.mdf”. Follow the below mentioned steps to manually rename the files:

    1. Firstly, run the following command to create a new database with name ”new_db”.
    2. CREATE DATABASE [new_db]
      CONTAINMENT = NONE
      ON PRIMARY
      ( NAME = 'name', FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\new_db.mdf',SIZE = 5MB , MAXSIZE = UNLIMITED, FILEGROWTH = 10MB )

      Thus, a new database is created with physical file “new_db”. The following steps can be used to rename SQL Server physical files name.

    3. Now, locate the physical location of file on your system using the following command:
    4. USE new_db
      GO
      SELECT file_id, name as [logical_file_name], physical_name
      FROM sys.database_files
    5. Also, the database should be brought to OFFLINE state because the files cannot be renamed in the online mode. Run the following command to bring database to offline state:
    6. USE [master];
      GO
      --Disconnect all existing session.
      ALTER DATABASE new_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE
      GO
      --Change database in to OFFLINE mode.
      ALTER DATABASE new_db SET OFFLINE
    7. Since the database is offline now, so browse to the location of the file as found from Step(1). Rename the file to desired name e.g., old_db.mdf.
    8. Now, update the system catalog for updating the new name of the physical file.
    9. ALTER DATABASE new_db MODIFY FILE (Name='new_db', FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\old_db.mdf') GO

      This updates the physical file name in system catalog file.

    10. Run the following command to bring the database in ONLINE mode:
    11. ALTER DATABASE new_db SET ONLINE
      Go
      ALTER DATABASE new_db SET MULTI_USER
      Go

      So, the database physical file name has been renamed to “old_db.mdf” and the database is also in the Online mode. The users can now work normally on the database to perform any operation.

    Conclusion

    The user may feel it necessary to rename physical file name in SQL Server due to any reason. However, to avoid confusion between the physical files and database, the users are always advised to rename SQL Server physical database files using T-SQL. All the detailed steps have been mentioned in the above section.

    How to find out highest table size in sql server 2014 ?

    SELECT
        t.NAME AS TableName,
        i.name as indexName,
        sum(p.rows) as RowCounts,
        sum(a.total_pages) as TotalPages,
        sum(a.used_pages) as UsedPages,
        sum(a.data_pages) as DataPages,
        (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB,
        (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB,
        (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
    FROM
        sys.tables t
    INNER JOIN    
        sys.indexes i ON t.OBJECT_ID = i.object_id
    INNER JOIN
        sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
    INNER JOIN
        sys.allocation_units a ON p.partition_id = a.container_id
    WHERE
        t.NAME NOT LIKE 'dt%' AND
        i.OBJECT_ID > 255 AND  
        i.index_id <= 1
    GROUP BY
        t.NAME, i.object_id, i.index_id, i.name
    ORDER BY
        TotalSpaceMB desc

    Batch script to take database users backup in sql server

    SQL Server Version:- SQL 2014

    Create a batch file which will be scheduled on task scheduler.

    set backuplogfilename=%date:~-7,2%-%date:~-10,2%-%date:~-4,4%-0%time:~1,1%%time:~3,2%%time:~6,2%
    SQLCMD.EXE -S localhost -U sa -P "sa@123" -i "E:\users.sql"  >> "E:\users_%backuplogfilename%.log"
    -- save and exit

    Now schedule the above .bat file in task scheduler


    Create a sql file lets say users.sql
    Content of users.sql

    USE master
    GO
    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

    exec dbo.sp_help_revlogin
    go

    Register a Connected Server using 2012 SQL Server Management Studio

    Register a Connected Server using 2012 SQL Server Management Studio :-

    By registering the server, you can save the connection information for servers that we access frequently. A server can be registered before connecting, or at the time of connection
    from Object Explorer.


    To register a connected server:-
    Open up sql server management studio 2012.
    In Object Explorer, right-click a server to which you already are connected, and then click Register.

    * Server name
    Enter the name you want to use for the registered server. Registering a local or remote server using SQL Server Management Studio lets you store the server connection information
    for future connections. This field defaults to the server name entered when you were connecting to the server. You can retain this server name or enter another easy-to-use
    name for the server.

    * Authentication
    There are two type of authentication available .
    a.Windows authentication
    b.Sql server authentication

    Choose anyone of above for the authentication method.

    * Server description
    Enter an optional description of the server. The maximum number of characters allowed is 250.

    * Save
    Click to save the information you have entered and create a registered server.





    Different SQL Server Roles

    Different SQL Server Roles:-

    Server Roles:-

    The Server Roles page lists all possible roles that can be assigned to the new login. The following options are available:
    bulkadmin:-
    Members of the bulkadmin fixed server role can run the BULK INSERT statement.

    dbcreator:-
    Members of the dbcreator fixed server role can create, alter, drop, and restore any database.

    diskadmin:-
    Members of the diskadmin fixed server role can manage disk files.

    processadmin:-
    Members of the processadmin fixed server role can terminate processes running in an instance of the Database Engine.

    public:-
    All SQL Server users, groups, and roles belong to the public fixed server role by default.

    securityadmin:-
    Members of the securityadmin fixed server role manage logins and their properties. They can GRANT, DENY, and REVOKE server-level permissions. They can also GRANT, DENY, and REVOKE
    database-level permissions. Additionally, they can reset passwords for SQL Server logins.

    serveradmin:-
    Members of the serveradmin fixed server role can change server-wide configuration options and shut down the server.

    setupadmin :-
    Members of the setupadmin fixed server role can add and remove linked servers, and they can execute some system stored procedures.

    sysadmin :-
    Members of the sysadmin fixed server role can perform any activity in the Database Engine.



    Database-Level Roles:-

    db_owner :- Members of the db_owner fixed database role can perform all configuration and maintenance activities on the database,
    and can also drop the database.

    db_securityadmin:- Members of the db_securityadmin fixed database role can modify role membership and manage permissions. Adding principals
    to this role could enable unintended privilege escalation.

    db_accessadmin :- Members of the db_accessadmin fixed database role can add or remove access to the database for Windows logins, Windows groups,
    and SQL Server logins.

    db_backupoperator :- Members of the db_backupoperator fixed database role can back up the database.

    db_ddladmin :- Members of the db_ddladmin fixed database role can run any Data Definition Language (DDL) command in a database.

    db_datawriter:- Members of the db_datawriter fixed database role can add, delete, or change data in all user tables.

    db_datareader :- Members of the db_datareader fixed database role can read all data from all user tables.

    db_denydatawriter :- Members of the db_denydatawriter fixed database role cannot add, modify, or delete any data in the user
    tables within a database.

    db_denydatareader :- Members of the db_denydatareader fixed database role cannot read any data in the user tables within a database.

    How to configure mail on SQL Server 2012

    Configure mail on SQL Server 2012



    Please share your ideas and opinions about this topic.

    If you like this post, then please share with others.
    Please subscribe on email for every updates on mail.
    Related Posts Plugin for WordPress, Blogger...