Working with XML in C# and SQL Server

Đôi khi một lập trình viên có thể nhận một task nhất định liên quan đến việc thao tác dữ liệu XML trên SQL Server, hoặc đơn giản cần insert một list data từ C# xuống data SQL. Khi đó chúng ta có thể chuyển list data thành một XML rồi thao tác dễ dàng. Bài viết này sẽ hữu ích trong những tình huống như vậy.

Thực hiện convert một object, list object trong C# thành XML

Chúng ta có một đối tượng là Student cần chuyển đổi.

public class Student     
{        
        public int Id { get; set; }         
        public string Name { get; set; }   
        public int Age { get; set; }           public string Phone { get; set; }           public string Email { get; set; }           public double? Score { get; set; }   
}

Danh sách các Students

 var students = new List
            {
                new Student{Id =1, Name="An", Age=18, Email="[email protected]", Phone="123456789", Score=6.5 },
                new Student{Id =2, Name="Binh", Age=19, Email="[email protected]", Phone="64641313", Score=9.5 },
                new Student{Id =3, Name="Canh", Age=20, Email="[email protected]", Phone="525252525", Score=8 },
                new Student{Id =4, Name="Dat", Age=21, Email="[email protected]", Phone="525252525", Score=5 },
                new Student{Id =5, Name="Em", Age=22, Email="[email protected]", Phone="252525256879", Score=6 },
            };

Tạo một class ConvertToXmlExtension để viết các function convert list to xml

public static class ConvertToXmlExtension
{
	public static string XmlElementToString<T>(this IEnumerable<T> items)
	{
		var xEle = new XElement("Root",
			  from item in items
			  select new XElement("Row", ToXElement(item)));
		return xEle.ToString(SaveOptions.None);
	}

	public static string XmlAttributeToString<T>(this IEnumerable<T> items)
	{
		var xEle = new XElement("Root",
			  from item in items
			  select new XElement("Row", ToXAttribute(item)));
		return xEle.ToString(SaveOptions.None);
	}

	private static IEnumerable<XElement> ToXElement<T>(T item)
	{
		var elements = new List<XElement>();
		var listProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !Attribute.IsDefined(x, typeof(XmlIgnoreAttribute)));

		foreach (var prop in listProperties)
		{
			var value = prop.GetValue(item, null);
                        if(value != null)
                        {
			    elements.Add(new XElement(prop.Name, value));
                        }
		}
		return elements;
	}

	private static IEnumerable<XAttribute> ToXAttribute<T>(T item)
	{
		var attributes = new List<XAttribute>();
		var listProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !Attribute.IsDefined(x, typeof(XmlIgnoreAttribute)));

		foreach (var prop in listProperties)
		{
			var value = prop.GetValue(item, null);
                        if(value != null) 
                        {
			   attributes.Add(new XAttribute(prop.Name, value));
                        }
		}
		return attributes;
	}
}

Kết quả sau khi gọi function XmlElementToString

var xml = students.XmlElementToString();
Console.WriteLine(xml);
<Root>
  <Row>
    <Id>1</Id>
    <Name>An</Name>
    <Age>18</Age>
    <Phone>123456789</Phone>
    <Email>[email protected]</Email>
    <Score>6.5</Score>
  </Row>
  <Row>
    <Id>2</Id>
    <Name>Binh</Name>
    <Age>19</Age>
    <Phone>64641313</Phone>
    <Email>[email protected]</Email>
    <Score>9.5</Score>
  </Row>
  <Row>
    <Id>3</Id>
    <Name>Canh</Name>
    <Age>20</Age>
    <Phone>525252525</Phone>
    <Email>[email protected]</Email>
    <Score>8</Score>
  </Row>
  <Row>
    <Id>4</Id>
    <Name>Dat</Name>
    <Age>21</Age>
    <Phone>525252525</Phone>
    <Email>[email protected]</Email>
    <Score>5</Score>
  </Row>
  <Row>
    <Id>5</Id>
    <Name>Em</Name>
    <Age>22</Age>
    <Phone>252525256879</Phone>
    <Email>[email protected]</Email>
    <Score>6</Score>
  </Row>
</Root>
var xml = students.XmlAttributeToString();
Console.WriteLine(xml); 
<Root>
  <Row Id="1" Name="An" Age="18" Phone="123456789" Email="[email protected]" Score="6.5" />
  <Row Id="2" Name="Binh" Age="19" Phone="64641313" Email="[email protected]" Score="9.5" />
  <Row Id="3" Name="Canh" Age="20" Phone="525252525" Email="[email protected]" Score="8" />
  <Row Id="4" Name="Dat" Age="21" Phone="525252525" Email="[email protected]" Score="5" />
  <Row Id="5" Name="Em" Age="22" Phone="252525256879" Email="[email protected]" Score="6" />
</Root>

Thực hiện thao tác với XML trong SQL Server

Đối với XML Element


DECLARE @XMLData XML
SET @XMLData ='
<Root>
  <Row>
    <Id>1</Id>
    <Name>An</Name>
    <Age>18</Age>
    <Phone>123456789</Phone>
    <Email>[email protected]</Email>
    <Score>6.5</Score>
  </Row>
  <Row>
    <Id>2</Id>
    <Name>Binh</Name>
    <Age>19</Age>
    <Phone>64641313</Phone>
    <Email>[email protected]</Email>
    <Score>9.5</Score>
  </Row>
  <Row>
    <Id>3</Id>
    <Name>Canh</Name>
    <Age>20</Age>
    <Phone>525252525</Phone>
    <Email>[email protected]</Email>
    <Score>8</Score>
  </Row>
  <Row>
    <Id>4</Id>
    <Name>Dat</Name>
    <Age>21</Age>
    <Phone>525252525</Phone>
    <Email>[email protected]</Email>
    <Score>5</Score>
  </Row>
  <Row>
    <Id>5</Id>
    <Name>Em</Name>
    <Age>22</Age>
    <Phone>252525256879</Phone>
    <Email>[email protected]</Email>
    <Score>6</Score>
  </Row>
</Root>'
SELECT Id = Node.Data.value('(Id)[1]', 'INT')
        , [Name] = Node.Data.value('(Name)[1]', 'VARCHAR(MAX)')
        , [Age] = Node.Data.value('(Age)[1]', 'INT')
		, [Email] = Node.Data.value('(Email)[1]', 'VARCHAR(MAX)')
		, [Phone] = Node.Data.value('(Phone)[1]', 'VARCHAR(MAX)')
		, [Score] = Node.Data.value('(Score)[1]', 'FLOAT')
FROM    @XMLData.nodes('/Root/Row') Node(Data)

Đối với XML Attribute

DECLARE @XMLData XML

SET @XMLData = '<Root>
  <Row Id="1" Name="An" Age="18" Phone="123456789" Email="[email protected]" Score="6.5" />
  <Row Id="2" Name="Binh" Age="19" Phone="64641313" Email="[email protected]" Score="9.5" />
  <Row Id="3" Name="Canh" Age="20" Phone="525252525" Email="[email protected]" Score="8" />
  <Row Id="4" Name="Dat" Age="21" Phone="525252525" Email="[email protected]" Score="5" />
  <Row Id="5" Name="Em" Age="22" Phone="252525256879" Email="[email protected]" Score="6" />
</Root>'

DECLARE @idoc INT

EXEC sp_xml_preparedocument @idoc OUTPUT
	,@XMLData

SELECT data.Id
	,data.Name
	,data.Age
	,data.Phone
	,data.Email
	,data.Score
FROM OPENXML(@idoc, '/Root/Row', 1) WITH (
		Id INT
		,Name NVARCHAR(50)
		,Age INT
		,Phone NVARCHAR(50)
		,Email NVARCHAR(50)
		,Score FLOAT
		) AS data

EXEC sp_xml_removedocument @idoc

Kết quả

Chúc các bạn thành công.

SQL Server Date Formats

One of the most frequently asked questions in SQL Server forums is how to format a datetime value or column into a specific date format.  Here’s a summary of the different date formats that come standard in SQL Server as part of the CONVERT function.  Following the standard date formats are some extended date formats that are often asked by SQL Server developers.

It is worth to note that the output of these date formats are of VARCHAR data types already and not of DATETIME data type.  With this in mind, any date comparisons performed after the datetime value has been formatted are using the VARCHAR value of the date and time and not its original DATETIME value.

Standard Date Formats
Date Format Standard SQL Statement Sample Output
Mon DD YYYY 1
HH:MIAM (or PM)
Default SELECT CONVERT(VARCHAR(20), GETDATE(), 100) Jan 1 2005 1:29PM 1
MM/DD/YY USA SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY] 11/23/98
MM/DD/YYYY USA SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY] 11/23/1998
YY.MM.DD ANSI SELECT CONVERT(VARCHAR(8), GETDATE(), 2) AS [YY.MM.DD] 72.01.01
YYYY.MM.DD ANSI SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD] 1972.01.01
DD/MM/YY British/French SELECT CONVERT(VARCHAR(8), GETDATE(), 3) AS [DD/MM/YY] 19/02/72
DD/MM/YYYY British/French SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY] 19/02/1972
DD.MM.YY German SELECT CONVERT(VARCHAR(8), GETDATE(), 4) AS [DD.MM.YY] 25.12.05
DD.MM.YYYY German SELECT CONVERT(VARCHAR(10), GETDATE(), 104) AS [DD.MM.YYYY] 25.12.2005
DD-MM-YY Italian SELECT CONVERT(VARCHAR(8), GETDATE(), 5) AS [DD-MM-YY] 24-01-98
DD-MM-YYYY Italian SELECT CONVERT(VARCHAR(10), GETDATE(), 105) AS [DD-MM-YYYY] 24-01-1998
DD Mon YY 1 SELECT CONVERT(VARCHAR(9), GETDATE(), 6) AS [DD MON YY] 04 Jul 06 1
DD Mon YYYY 1 SELECT CONVERT(VARCHAR(11), GETDATE(), 106) AS [DD MON YYYY] 04 Jul 2006 1
Mon DD, YY 1 SELECT CONVERT(VARCHAR(10), GETDATE(), 7) AS [Mon DD, YY] Jan 24, 98 1
Mon DD, YYYY 1 SELECT CONVERT(VARCHAR(12), GETDATE(), 107) AS [Mon DD, YYYY] Jan 24, 1998 1
HH:MM:SS SELECT CONVERT(VARCHAR(8), GETDATE(), 108) 03:24:53
Mon DD YYYY HH:MI:SS:MMMAM (or PM) 1 Default +
milliseconds
SELECT CONVERT(VARCHAR(26), GETDATE(), 109) Apr 28 2006 12:32:29:253PM 1
MM-DD-YY USA SELECT CONVERT(VARCHAR(8), GETDATE(), 10) AS [MM-DD-YY] 01-01-06
MM-DD-YYYY USA SELECT CONVERT(VARCHAR(10), GETDATE(), 110) AS [MM-DD-YYYY] 01-01-2006
YY/MM/DD SELECT CONVERT(VARCHAR(8), GETDATE(), 11) AS [YY/MM/DD] 98/11/23
YYYY/MM/DD SELECT CONVERT(VARCHAR(10), GETDATE(), 111) AS [YYYY/MM/DD] 1998/11/23
YYMMDD ISO SELECT CONVERT(VARCHAR(6), GETDATE(), 12) AS [YYMMDD] 980124
YYYYMMDD ISO SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD] 19980124
DD Mon YYYY HH:MM:SS:MMM(24h) 1 Europe default + milliseconds SELECT CONVERT(VARCHAR(24), GETDATE(), 113) 28 Apr 2006 00:34:55:190 1
HH:MI:SS:MMM(24H) SELECT CONVERT(VARCHAR(12), GETDATE(), 114) AS [HH:MI:SS:MMM(24H)] 11:34:23:013
YYYY-MM-DD HH:MI:SS(24h) ODBC Canonical SELECT CONVERT(VARCHAR(19), GETDATE(), 120) 1972-01-01 13:42:24
YYYY-MM-DD HH:MI:SS.MMM(24h) ODBC Canonical
(with milliseconds)
SELECT CONVERT(VARCHAR(23), GETDATE(), 121) 1972-02-19 06:35:24.489
YYYY-MM-DDTHH:MM:SS:MMM ISO8601 SELECT CONVERT(VARCHAR(23), GETDATE(), 126) 1998-11-23T11:25:43:250
DD Mon YYYY HH:MI:SS:MMMAM 1 Kuwaiti SELECT CONVERT(VARCHAR(26), GETDATE(), 130) 28 Apr 2006 12:39:32:429AM 1
DD/MM/YYYY HH:MI:SS:MMMAM Kuwaiti SELECT CONVERT(VARCHAR(25), GETDATE(), 131) 28/04/2006 12:39:32:429AM
Here are some more date formats that does not come standard in SQL Server as part of the CONVERT function.

Extended Date Formats
Date Format SQL Statement Sample Output
YY-MM-DD
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 8) AS [YY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(8), GETDATE(), 11), ‘/’, ‘-‘) AS [YY-MM-DD]
99-01-24
YYYY-MM-DD
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]
SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 111), ‘/’, ‘-‘) AS [YYYY-MM-DD]
1999-01-24
MM/YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 3), 5) AS [MM/YY]
SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 3), 4, 5) AS [MM/YY]
08/99
MM/YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 103), 7) AS [MM/YYYY] 12/2005
YY/MM SELECT CONVERT(VARCHAR(5), GETDATE(), 11) AS [YY/MM] 99/08
YYYY/MM SELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM] 2005/12
Month DD, YYYY 1 SELECT DATENAME(MM, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 107), 9) AS [Month DD, YYYY] July 04, 2006 1
Mon YYYY 1 SELECT SUBSTRING(CONVERT(VARCHAR(11), GETDATE(), 113), 4, 8) AS [Mon YYYY] Apr 2006 1
Month YYYY 1 SELECT DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [Month YYYY] February 2006 1
DD Month 1 SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) AS [DD Month] 11 September 1
Month DD 1 SELECT DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(DAY(GETDATE()) AS VARCHAR(2)) AS [Month DD] September 11 1
DD Month YY 1 SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) + ‘ ‘ + RIGHT(CAST(YEAR(GETDATE()) AS VARCHAR(4)), 2) AS [DD Month YY] 19 February 72 1
DD Month YYYY 1 SELECT CAST(DAY(GETDATE()) AS VARCHAR(2)) + ‘ ‘ + DATENAME(MM, GETDATE()) + ‘ ‘ + CAST(YEAR(GETDATE()) AS VARCHAR(4)) AS [DD Month YYYY] 11 September 2002 1
MM-YY SELECT RIGHT(CONVERT(VARCHAR(8), GETDATE(), 5), 5) AS [MM-YY]
SELECT SUBSTRING(CONVERT(VARCHAR(8), GETDATE(), 5), 4, 5) AS [MM-YY]
12/92
MM-YYYY SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 105), 7) AS [MM-YYYY] 05-2006
YY-MM SELECT RIGHT(CONVERT(VARCHAR(7), GETDATE(), 120), 5) AS [YY-MM]
SELECT SUBSTRING(CONVERT(VARCHAR(10), GETDATE(), 120), 3, 5) AS [YY-MM]
92/12
YYYY-MM SELECT CONVERT(VARCHAR(7), GETDATE(), 120) AS [YYYY-MM] 2006-05
MMDDYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 1), ‘/’, ”) AS [MMDDYY] 122506
MMDDYYYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 101), ‘/’, ”) AS [MMDDYYYY] 12252006
DDMMYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 3), ‘/’, ”) AS [DDMMYY] 240702
DDMMYYYY SELECT REPLACE(CONVERT(VARCHAR(10), GETDATE(), 103), ‘/’, ”) AS [DDMMYYYY] 24072002
Mon-YY 1 SELECT REPLACE(RIGHT(CONVERT(VARCHAR(9), GETDATE(), 6), 6), ‘ ‘, ‘-‘) AS [Mon-YY] Sep-02 1
Mon-YYYY 1 SELECT REPLACE(RIGHT(CONVERT(VARCHAR(11), GETDATE(), 106), 8), ‘ ‘, ‘-‘) AS [Mon-YYYY] Sep-2002 1
DD-Mon-YY 1 SELECT REPLACE(CONVERT(VARCHAR(9), GETDATE(), 6), ‘ ‘, ‘-‘) AS [DD-Mon-YY] 25-Dec-05 1
DD-Mon-YYYY 1 SELECT REPLACE(CONVERT(VARCHAR(11), GETDATE(), 106), ‘ ‘, ‘-‘) AS [DD-Mon-YYYY] 25-Dec-2005 1

1 To make the month name in upper case, simply use the UPPER string function.

CSDL tên Quốc gia, tỉnh thành phố thị xã quận huyện, xã phường Việt Nam

  • Thông tin 245quốc gia trên thế giới
  • Thông tin 64 tỉnh thành  phố Việt Nam
  • Thông tin 697 quận huyện / thị xã
  • Thông tin 11110 xã phường

Nguồn tài liệu tham khảo: cổng thông tin điện tử các tỉnh thành, quận huyện, từ điển bách khoa toàn thư điện tử Wikipedia.
Định dạng dữ liệu: bảng cơ sở dữ liệu SQL
Mục đích: chia sẻ giúp các bạn webmaster đang muốn lấy một nguồn thông tin chuẩn mực về tên các đơn vị hành chính cho các dự án website, cổng thông tin điện tử ….

Download

 

Chúc các bạn thành công

T SQL Query Ultilities

— Find all Column not in Table

select name from sys.tables
where name not in
(
SELECT t.name 
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE 'IsDeleted'
)

— Deleting all duplicate rows but keeping one [duplicate]

WITH cte AS (
  SELECT FirstName, 
     row_number() OVER(PARTITION BY FirstName ORDER BY FirstName) AS [rn]
  FROM Client
)
DELETE cte WHERE [rn] > 1

— Adding a column to all user tables in T-SQL

exec sp_msforeachtable 'alter table ? add IsDeleted bit not null default 0';

--- Adding a column to all user table if not exists
EXEC sp_msforeachtable '
if not exists (select name from sys.tables
where name not in(SELECT t.name FROM sys.columns c
				JOIN sys.tables t ON c.object_id = t.object_id
				WHERE c.name LIKE ''IsDeleted'')
) 
begin
    ALTER TABLE ? ADD IsDeleted bit NOT NULL DEFAULT 0;
end';

 

SQL Server : random date in specific range (including random hours, minutes,…)

DECLARE @FromDate DATETIME = DATEADD(DAY, -10, GETDATE())
DECLARE @ToDate DATETIME = DATEADD(DAY, -12, GETDATE())

DECLARE @Seconds INT = DATEDIFF(SECOND, @FromDate, @ToDate)
DECLARE @Random INT = ROUND(((@Seconds-1) * RAND()), 0)
DECLARE @Milliseconds INT = ROUND((999 * RAND()), 0)

declare @newDate datetime = DATEADD(MILLISECOND, @Milliseconds, DATEADD(SECOND, @Random, @FromDate))

select @newDate

How to convert GMT(UTC) Datetime to Local Datetime?

I have an insert proc that passes in GETDATE() as one of the values because each insert also stores when it was inserted. This is hosted on SQL Azure – which uses GMT.

Now, when I am receiving messages, I have the GMT date stored for each of them in their timestamp columns, how do I convert this to the local datetime for wherever you are when you are accessing my page?

You could do something like this:

declare @InputUtcDateTime datetime2 = '2016-06-24 06:30:18'

declare @LocalDateTime datetime2 = dateadd(minute, datepart(TZoffset, sysdatetimeoffset()), @InputUtcDateTime)
print @LocalDateTime

or

declare @InputUtcDateTime datetime2 = '2016-06-24 06:30:18'

declare @LocalDateTime datetime2 = dateadd(minute, datediff(minute, sysutcdatetime(), sysdatetime()), @InputUtcDateTime)
print @LocalDateTime

My T-SQL

DECLARE @utcdate DATETIME = '2016-06-24 06:30:18.127'
SELECT DATEADD(hh,DATEDIFF(hh,GETUTCDATE(),GETDATE()),@utcdate) AS currentLocalTime;

Real i used

update [Order]
set StockDate =  DATEADD(hh,DATEDIFF(hh,GETUTCDATE(),GETDATE()),StockDate),
OrderDate = DATEADD(hh,DATEDIFF(hh,GETUTCDATE(),GETDATE()),OrderDate),
ShipDate =  DATEADD(hh,DATEDIFF(hh,GETUTCDATE(),GETDATE()),ShipDate)

 

SQL Server CONVERT() Function

Definition and Usage

The CONVERT() function is a general function that converts an expression of one data type to another.

The CONVERT() function can be used to display date/time data in different formats.

Syntax

CONVERT(data_type(length),expression,style)

 

Value Description
data_type(length) Specifies the target data type (with an optional length)
expression Specifies the value to be converted
style Specifies the output format for the date/time (see table below)

The style value can be one of the following values:

Without century With century Input/Output Standard
0 or 100 mon dd yyyy hh:miAM (or PM) Default
1 101 1 = mm/dd/yy
101 = mm/dd/yyyy
USA
2 102 2 = yy.mm.dd
102 = yyyy.mm.dd
ANSI
3 103 3 = dd/mm/yy
103 = dd/mm/yyyy
British/French
4 104 4 = dd.mm.yy
104 = dd.mm.yyyy
German
5 105 5 = dd-mm-yy
105 = dd-mm-yyyy
Italian
6 106 6 = dd mon yy
106 = dd mon yyyy
7 107 7 = Mon dd, yy
107 = Mon dd, yyyy
8 108 hh:mm:ss
9 or 109 mon dd yyyy hh:mi:ss:mmmAM (or PM) Default + millisec
10 110 10 = mm-dd-yy
110 = mm-dd-yyyy
USA
11 111 11 = yy/mm/dd
111 = yyyy/mm/dd
Japan
12 112 12 = yymmdd
112 = yyyymmdd
ISO
13 or 113 dd mon yyyy hh:mi:ss:mmm (24h) Europe default + millisec
14 114 hh:mi:ss:mmm (24h)
20 or 120 yyyy-mm-dd hh:mi:ss (24h) ODBC canonical
21 or 121 yyyy-mm-dd hh:mi:ss.mmm (24h) ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset
126 yyyy-mm-ddThh:mi:ss.mmm (no spaces) ISO8601
127 yyyy-mm-ddThh:mi:ss.mmmZ (no spaces) ISO8601 with time zone Z
130 dd mon yyyy hh:mi:ss:mmmAM Hijiri
131 dd/mm/yy hh:mi:ss:mmmAM Hijiri

Example

The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time:

CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)

The result would look something like this:

Nov 04 2014 11:45 PM
11-04-14
11-04-2014
04 Nov 14
04 Nov 2014
04 Nov 2014 11:45:34:243

How To Repair A Suspect Database In MSSQL

How To Repair A Suspect Database In MS SQL

Issue
You have a database in MS SQL that is tagged as (suspect) and you are unable to connect to the database.

Possible Causes

  • The database could have become corrupted.
  • There is not enough space available for the SQL Server to recover the database during startup.
  • The database cannot be opened due to inaccessible files or insufficient memory or disk space.
  • The database files are being held by operating system, third party backup software etc.
  • There was an unexpected SQL Server Shutdown, power failure or a hardware failure.

Resolution
These steps require you to have Microsoft SQL Server Management Studio installed on your computer.  If you do not have this installed please follow the steps outlined in the following article: How To Connect To Your MS SQL Database

Always back up the website before making any changes to the database . Shared hosting customers can do this through the Control Panel. Refer to Back Up Your Website Using Plesk. Dedicated server customers can back up the site either through the Control Panel, or through the Control Suite. Refer to How to Back Up a Domain Using Control Suite.

  1. Open Microsoft SQL Server Management Studio and connect to your database
  2. Click the New Query button
  3. Paste the following SQL script into your New Query page replacing [YourDatabase] with the name of your database.
    EXEC sp_resetstatus [YourDatabase];
    ALTER DATABASE [YourDatabase] SET EMERGENCY
    DBCC checkdb([YourDatabase])
    ALTER DATABASE [YourDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
    DBCC CheckDB ([YourDatabase], REPAIR_ALLOW_DATA_LOSS)
    ALTER DATABASE [YourDatabase] SET MULTI_USER
  4. Click Execute

Your database should no longer be tagged as (suspect) and you should be able to access it.

How to Install SQL Server Management Studio

SQL Server Management Studio (SSMS) is the official and preferred client user interface which can be used to manage, configure, deploy, upgrade and administer a SQL Server instance. The tool interface is quite user friendly and comprehensive. It is shipped with every SQL Server version and is regularly updated and enhanced. If you are planning on learning how to use SQL Server from scratch, consider using SQL Server Management studio as a first step on your journey to learning SQL Server.

Why is this installation so important? Like any other technology, in SQL Server too we need to focus on theoretical knowledge as well as hands-on practice and in order to achieve hands-on practice, SQL Server Management Studio (SSMS) is essential.

In this SQL Server Management Studio tutorial, I will demonstrate how to install SQL Server Management Studio (SSMS) in 12 easy steps. This tutorial will help you to perform the installation process of the SQL Server Management Studio (SSMS).

Step 1:

First of all you need to download SQL Server Management Studio (SSMS) installation files (SQLManagementStudio_x64_ENU.exe / SQLManagementStudio_x86_ENU.exe) from the SQL Server download page depending on your server type (x64,x86), and keep it in a separate folder.

Figure illustrating the SQL Server Management Studio download page

Step 2:

Once you downloaded the respective file as per your server type, you need to execute it. It will then take you to the first screen namely SQL Server Installation Center as shown below. This is the primary installation screen of SQL Server. Other SQL server tools installations can be launched from here as well. Once you are on this screen, you need to select “New SQL Server stand-alone installation or add features to an existing installation” to proceed with the installation.

Selecting New SQL Server stand-alone installation or add features to an existing installation from the SQL Server Installation Center

Step 3:

Once you select the “New SQL Server stand-alone installation or add features to an existing installation” option, it will check the setup rules (pre-requisites) on the server and take you to the license terms screen. The license terms must be read and accepted like with any other application’s license terms. Please note that your server must pass the setup rules in order to proceed with the installation.

SQL Server 2012 Setup - accepting license terms

Step 4:

Once you accept the license terms, it is time to scan all the available product updates. The required updates, size and details will be displayed. However, if you need further details, you can select More Information which will take you to the support page where you will find all the details related to the updates. You can ignore these updates by deselecting the ‘Include SQL Server product updates’ option at this stage.

I highly recommend that you download these updates along with the installation. This step might take some time depending on the size of the update files.

SQL Server product updates dialog

Step 5:

The next step is the Install Setup Files step, where SQL Server Management Studio (SSMS) setup will download, extract and install all necessary setup files to your server.

Figure illustrating the Install Setup Files step

Step 6:

Once SQL Server Management Studio (SSMS) setup is done with the install setup files, it verifies the setup support rules in order to proceed. It then takes you to the feature selection screen. This is a very comprehensive screen which has detailed information about each feature. When we run the SQL Server Management Studio (SSMS) installation, it selects Management Tools by default, so you do not need to select anything here. In addition you can select Management tools – Basic. To get more information on this feature you can view the detailed feature description on right hand side.

This screen also gives you the ability to select and deselect all features in one go. This saves lots of time when you need to install multiple features. It also provides detailed information about the prerequisites, the selected features, which prerequisites have already been installed and which will be installed through this installation. You just need to click on the Next button to continue.

Figure illustrating Feature Selection step in SQL Server 2012 setup

Step 7:

In this step, SQL Server Management Studio (SSMS) setup will check the installation rules (pre-requisite for the SSMS). Just click on the Next button to continue.

Figure illustrating the Installation Rules step in SQL Server 2012 Management Studio Setup

Step 8:

In this step SQL Server Management Studio (SSMS) setup will verify the disk space. Please make sure that you have sufficient disk space available. Not having sufficient disk space may result in a faulty installation. Just click on the Next button to continue.

Figure illustrating the Disk Space Requirements step in SQL Server Management Studio 2012 Setup

Step 9:

In this step, you have the opportunity to decide whether or not to send the error notifications to Microsoft. This is highly recommended in order to help Microsoft improve future releases and to fix any bugs in the existing release.

Figure illustrating SQL Server 2012 Setup step where you decide whether or not to send the error notifications to Microsoft

Step 10:

Once you click on the Next button, setup checks the installation configuration rules and if it passed, setup continues. This step will take some time to install SQL Server Management Studio. You can sit back and relax :)

Figure illustrating the Installation Progress in SQL Server Management Studio 2012 Setup

Step 11:

This step displays the installation status of SQL Server Management Studio (SSMS) along with each feature, like a summary. This screen really helps to view what has been installed and what has not. In case one of the features could not be installed, you can re-run the same installation procedure and install that particular feature.

Figure illustrating what has been installed and what has not in SQL Server Management Studio setup

Step 12:

In order to check whether SQL Server Management Studio (SSMS) has been installed successfully, you need to select start menu of your server and then further select the SQL Server 2012 menu. You will find the link to SQL Server Management Studio there.

Link to SQL Server Management Studio there

Alternate Option:

Please note that above installation procedure is for a standalone installation of SQL Server Management Studio (SSMS). However you can install SQL Server Management Studio (SSMS) along with the SQL Server installation as well, just ensure that you have selected Management Tools in the feature screen as shown below.

Alternate option - choosing toinstall SQL Server Management Studio (SSMS) along with the SQL Server installation

Conclusion:

As you can see, the SQL Server Management Studio (SSMS) installation is not complicated at all, it is quite user friendly. You just need to read the instructions carefully and follow them accurately, for a smooth installation.

Useful resources:
SQL Server Management Studio (SSMS) Basics
Step-by-Step: Installing SQL Server Management Studio 2008 Express after Visual Studio 2010
SQL Server download page

– See more at: http://www.sqlshack.com/sql-server-management-studio-step-step-installation-guide/#sthash.ErnTqH07.dpuf

Sql Scripts – Delete all Tables, Procedures, Views and Functions

Trong môi trường chia sẻ MSSQL thường bạn không có quyền xóa một CSDL để tạo lại khi thấy nó không phù hợp. Lúc đó chúng ta thường ngay lập tức nghĩ đến giải pháp xóa hết các bảng (table), thủ tục (stored procedure)… để tạo lại dữ liệu mới. Trong trường hợp table, stored procedure của bạn quá nhiều (hàng trăm table chẳng hạn)  thì điều đó thật mất thời gian & nhàm chán.

Thật may mắn, MS cung cấp cho chúng ta những dòng lệnh trong Query để thực hiện xóa một lần toàn bộ table hay stored procedure một cách nhanh chóng & sạch sẽ.

Delete All Tables

--Delete All Keys

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

Delete All Stored Procedures

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'p'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
            if @procName <> 'DeleteAllProcedures'
                  exec('drop procedure ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

Delete All Views

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'v'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop view ' + @procName)
                  fetch next from cur into @procName
      end
close cur
deallocate cur

 

Delete All Functions

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'fn'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop function ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur
 Chúc các bạn thành công!