Showing posts with label mssql. Show all posts
Showing posts with label mssql. Show all posts

Thursday, 24 November 2011

mssql - compare two datetime fields


problem

mssql - compare two datetime
Mssql, compare two datetime fields, if their values are close, if are in 24h difference and do on
---
> dennis
difficulty level

1/10 :)))
compatibility

mssql
solution

In mssql, the datetime fields are actually numeric with decimals. The integer part in the “days”. So if you want to compare two dates compare the integer part as bellow

-- compare if the item is sold 24h before the item is modified
Select * from items
Where ModificationDate<SaleDate-1

-- find person(s) that born on 12/11/2010 (not exactly on the same, with at least 12 hours difference)
Select * from persons
Where birthdate-0.5>=’2010-12-11’ and birthdate+0.5<=’2010-12-11’

Wednesday, 2 November 2011

MSSQL - how to copy tables and data


problem

MSSQL - how to copy
- How to copy a table’s structure to another database?
- How to create a table with the same structure (fields) on the
- How to copy the data of the table to another table?
difficulty level

4/10 :)
compatibility

general
solution

How to copy a table’s structure to another database?
The follow code, not only copy’s the structure but also copies and the records of it. You may filter the data applying a “where” as I do here.
--
Do like:
SELECT * INTO [TargetDatabase].[dbo].[MyTable]
FROM [SourceDatabase].[dbo].[MyTable]
where [SourceDatabase].[dbo].[MyTable].CustomerCode='01'; -- where is optional


How to create a table with the same structure (fields) on the same database?
(Like you did previously!)
--Do like:
SELECT * INTO MyNewTable
FROM MySourceTable
where MySourceTable.CustomerCode='01'; -- where is optional

How to copy the data of the table to another table?
--Syntax:
INSERT INTO TargetTable( <field list> )
SELECT <field list> FROM SourceTable
--Do like:
INSERT INTO NewCustomers
( Company, Branch, Name )
SELECT
Company, Branch, Name
FROM Customers
Where Branch=’01’; -- where is optional