SQL Server 2016 Temporal Tables are Blank - sql-server-2016

I am trying to create a Temporal Table in SQL Server 2016. The Database is linked to an Azure Data factory which is updated regularly.
I am able to successfully 'create' the Temporal Table, but whenever I try to Select Rows from the table they are blank.
Code for Temporal Table Below:
CREATE TABLE [dbo].[RecoTemp_Test2]
(
[ObservationID] [varchar](100) NULL,
[ObservationTitle] [text] NULL,
[RecoReleaseDate] [date] NULL,
[RecoIsReleased] [varchar](100) NULL,
[ObservationRootCause] [text] NULL,
[EntityID] [varchar](100) NULL,
[AuditID] [varchar](100) NULL,
[RecoID] [varchar](100) NOT NULL,
[ObservationDescription] [text] NULL,
[ObservationBusinessImpactRisk] [text] NULL,
[RecoCode] [varchar](100) NULL,
[RecoTMState] [varchar](100) NULL,
[RecoTMSubState] [varchar](100) NULL,
[RecoPriority] [varchar](100) NULL,
[RecoEffortToComplete] [varchar](100) NULL,
[RecoProgressRate] [varchar](100) NULL,
[RecoLastFollowUpComments] [text] NULL,
[RecoLastFollowUpUserID] [varchar](100) NULL,
[RecoLastFollowUpUserName] [varchar](100) NULL,
[RecoLastFollowUpDate] [date] NULL,
[Reco3Pillars] [varchar](100) NULL,
[RecoTargetDate] [date] NULL,
[RecoTargetDateRevised] [date] NULL,
[RecoLastImplementedDate] [date] NULL,
[RecoLastClosedDate] [date] NULL,
[RecoDescription] [text] NULL,
[RecoManagementActionPlan] [text] NULL,
[RecoExpectedDeliverables] [text] NULL,
[RecoIsPastDue] [varchar](100) NULL,
[RecoIsPastDueEoY] [varchar](100) NULL,
[RecoStatus] [varchar](100) NULL,
[RecoStatusLvl1] [varchar](100) NULL,
[RecoProgressRateLabel] [varchar](100) NULL,
[RecoClosingDeadline] [date] NULL,
[RecoOrigin] [varchar](100) NULL,
[RecoIssuedDate] [date] NULL,
SysStartTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL,
SysEndTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime),
PRIMARY KEY CLUSTERED ([RecoID] ASC)
)
WITH
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[RecoTemp_Test2_Hist])
)

Related

Brent Ozar's SQL Check Scripts - Memory/CPU/IO Concerns?

How careful do I need to be using Brent Ozar's free SQL health check scripts on a SQL Server 2016 production machine that's very full and very busy already? Has anyone run into memory, CPU or I/O issues running any of the following? Thanks for any feedback.
sp_Blitz
sp_BlitzCache
sp_BlitzFirst
sp_BlitzIndex
sp_BlitzLock
sp_BlitzQueryStore
sp_BlitzWho
sp_WhoIsActive (Adam Machanic)
I would not be without it. We have Redgate and I use Brents tools more often.
Our database is 3 Tb and has approx. 1500 queries per second and have never experienced any problems.
Made a custom sp_BlitzWho_Ext which relys on the sp_BlitzWho.
It takes the result of sp_BlitzWho. Puts it in a temp table so I can add a filter. Also cursors are identified and converted so you can see the actual query.
The SQL for dropping the plan_cache of each of them are there - so whenever we get a dumb plan its easy to find and drop the right one.
It now only takes 5 seconds to identify the culprit and get the plan dropped.
First I created a Function to get the query text from the Cursor
create function [dbo].[CursorQuery]
(
#session_id int
) returns nvarchar(255)
as
begin
declare #ret nvarchar(255) = null
SELECT #ret = t.text
FROM sys.dm_exec_cursors (#session_id) c
LEFT JOIN sys.dm_exec_sessions AS es ON c.session_id = es.session_id
CROSS APPLY sys.dm_exec_sql_text (c.sql_handle) t
return #ret
end
Then the stored procedure
CREATE PROCEDURE [dbo].[sp_BlitzWho_Ext]
AS
BEGIN
CREATE TABLE #BlitzWhoResult
(
[run_date] VARCHAR(255),
[elapsed_time] [varchar](41) NULL,
[session_id] [smallint] NOT NULL,
[database_name] [nvarchar](128) NULL,
[query_text] [nvarchar](max) NULL,
[query_plan] [xml] NULL,
[live_query_plan] [xml] NULL,
[query_cost] [float] NULL,
[status] [nvarchar](30) NOT NULL,
[wait_info] [nvarchar](max) NULL,
[top_session_waits] [nvarchar](max) NULL,
[blocking_session_id] [smallint] NULL,
[open_transaction_count] [int] NULL,
[is_implicit_transaction] [int] NOT NULL,
[nt_domain] [nvarchar](128) NULL,
[host_name] [nvarchar](128) NULL,
[login_name] [nvarchar](128) NOT NULL,
[nt_user_name] [nvarchar](128) NULL,
[program_name] [nvarchar](128) NULL,
[fix_parameter_sniffing] [nvarchar](150) NULL,
[client_interface_name] [nvarchar](32) NULL,
[login_time] [datetime] NOT NULL,
[start_time] [datetime] NULL,
[request_time] [datetime] NULL,
[request_cpu_time] [int] NULL,
[request_logical_reads] [bigint] NULL,
[request_writes] [bigint] NULL,
[request_physical_reads] [bigint] NULL,
[session_cpu] [int] NOT NULL,
[session_logical_reads] [bigint] NOT NULL,
[session_physical_reads] [bigint] NOT NULL,
[session_writes] [bigint] NOT NULL,
[tempdb_allocations_mb] [decimal](38, 2) NULL,
[memory_usage] [int] NOT NULL,
[estimated_completion_time] [bigint] NULL,
[percent_complete] [real] NULL,
[deadlock_priority] [int] NULL,
[transaction_isolation_level] [varchar](33) NOT NULL,
[degree_of_parallelism] [smallint] NULL,
[last_dop] [bigint] NULL,
[min_dop] [bigint] NULL,
[max_dop] [bigint] NULL,
[last_grant_kb] [bigint] NULL,
[min_grant_kb] [bigint] NULL,
[max_grant_kb] [bigint] NULL,
[last_used_grant_kb] [bigint] NULL,
[min_used_grant_kb] [bigint] NULL,
[max_used_grant_kb] [bigint] NULL,
[last_ideal_grant_kb] [bigint] NULL,
[min_ideal_grant_kb] [bigint] NULL,
[max_ideal_grant_kb] [bigint] NULL,
[last_reserved_threads] [bigint] NULL,
[min_reserved_threads] [bigint] NULL,
[max_reserved_threads] [bigint] NULL,
[last_used_threads] [bigint] NULL,
[min_used_threads] [bigint] NULL,
[max_used_threads] [bigint] NULL,
[grant_time] [varchar](20) NULL,
[requested_memory_kb] [bigint] NULL,
[grant_memory_kb] [bigint] NULL,
[is_request_granted] [varchar](39) NOT NULL,
[required_memory_kb] [bigint] NULL,
[query_memory_grant_used_memory_kb] [bigint] NULL,
[ideal_memory_kb] [bigint] NULL,
[is_small] [bit] NULL,
[timeout_sec] [int] NULL,
[resource_semaphore_id] [smallint] NULL,
[wait_order] [varchar](20) NULL,
[wait_time_ms] [varchar](20) NULL,
[next_candidate_for_memory_grant] [varchar](3) NOT NULL,
[target_memory_kb] [bigint] NULL,
[max_target_memory_kb] [varchar](30) NULL,
[total_memory_kb] [bigint] NULL,
[available_memory_kb] [bigint] NULL,
[granted_memory_kb] [bigint] NULL,
[query_resource_semaphore_used_memory_kb] [bigint] NULL,
[grantee_count] [int] NULL,
[waiter_count] [int] NULL,
[timeout_error_count] [bigint] NULL,
[forced_grant_count] [varchar](30) NULL,
[workload_group_name] [sysname] NULL,
[resource_pool_name] [sysname] NULL,
[context_info] [varchar](128) NULL,
[query_hash] [binary](8) NULL,
[query_plan_hash] [binary](8) NULL,
[sql_handle] [varbinary] (64) NULL,
[plan_handle] [varbinary] (64) NULL,
[statement_start_offset] INT NULL,
[statement_end_offset] INT NULL
)
INSERT INTO #BlitzWhoResult
EXEC [dbo].[sp_BlitzWho] #ShowSleepingSPIDs = 1, #ExpertMode = 1, #MinElapsedSeconds = 1
SELECT [program_name],
[session_id],
CASE WHEN [query_text] LIKE 'FETCH API_CURSOR%'
THEN CursorQuery(session_id)
ELSE query_text
END AS [query_text],
[query_plan],
[fix_parameter_sniffing] AS [drop_cached_plan_sql],
[status],
[wait_info],
[login_name]
from #BlitzWhoResult
where database_name = 'PUT_YOUR_DATABASENAME_HERE' -- and... add more filters?
DROP TABLE #BlitzWhoResult
END
So.. I really enjoy Brents tool as well as his videos and sense of humour

SQL Between Function - Wrong Data is reflecting

I am trying to extract the data using between function but wrong data is reflecting
below SQL query i am using,
select * from ORDERSTATUS where ORDERDATE BETWEEN '25-07-2017' AND '31-08-2017';
Also when i run below sql query to extract the data of particular date, i am getting correct output.
select * from ORDERSTATUS where ORDERDATE = '31-08-2017'
Please help me....
and below is the design of my table,
[VENCD] [varchar](50) NOT NULL,
[VENNAME] [varchar](255) NOT NULL,
[ITEMCD] [varchar](50) NOT NULL,
[ITEMNAME] [varchar](255) NOT NULL,
[SKUCD] [varchar](50) NULL,
[SKUNAME] [varchar](255) NULL,
[OORDERNO] [varchar](50) NOT NULL,
[INVNO] [varchar](50) NULL,
[OQTY] [int] NOT NULL,
[COD] [int] NOT NULL,
[SELLINGPRICE] [int] NOT NULL,
[ORDERTYPE] [varchar](50) NOT NULL,
[DSP] [varchar](50) NOT NULL,
[DOCKETNO] [varchar](50) NULL,
[MANIFESTID] [varchar](100) NULL,
**[ORDERDATE] [varchar](50) NOT NULL,**
[CANCELDATE] [varchar](50) NULL,
[SHIPP_INST_DATE] [varchar](50) NULL,
[INVOUTDATE] [varchar](50) NULL,
[PICKUPDATE] [varchar](50) NULL,
[REALDELDATE] [varchar](50) NULL,
[DELCOMPDATE] [varchar](50) NULL,
[RETURNREGDATE] [varchar](50) NULL,
[SHIPP_CANCELDATE] [varchar](50) NULL,
[RTODATE] [varchar](50) NULL,
[DRDATE] [varchar](50) NULL,
[PROSSSTAGE] [varchar](255) NOT NULL,
[REFUND] [varchar](50) NOT NULL,
[CHNLCODE] [varchar](50) NOT NULL,
[CHNLCLASS] [varchar](50) NOT NULL,
[HLCN] [varchar](50) NULL,
[MLCN] [varchar](50) NULL,
[COMMPERC] [int] NULL,
[EXCHCANCELDATE] [varchar](50) NULL,
[RETURNCANCELDATE] [varchar](50) NULL,
[TYPE] [varchar](50) NULL
Can you change where clause with this?
CONVERT (DATETIME, ORDERDATE, 105) BETWEEN '20170725' AND '20170831';
Just use :
WHERE CONVERT(DATE, ORDERDATE) BETWEEN '20170725' AND '20170831'

Same query but different execution plans, same server

I made a copy of a table with the same indexes in the same database of the same server.
Then it executes the same query in one table and in the other but the execution plan is different.
Why?
These are my queries:
select top 1 * from SFMatl
where AppUpdated = 0 and UpdLock = 0 and CompanyId = 'ent'
order by recid
select top 1 * from SFMatl_Backup20042017
where AppUpdated = 0 and UpdLock = 0 and CompanyId = 'ent'
order by recid
And these execution plans:
Query1
Query2
My create tables:
/****** Object: Table [dbo].[SFMatl_Backup20042017] Script Date: 20/04/2017 14:40:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SFMatl_Backup20042017](
[RecId] [int] NOT NULL,
[CompanyId] [char](3) NOT NULL,
[PrOdId] [varchar](10) NOT NULL,
[OprNum] [tinyint] NOT NULL,
[WrkCtrId] [varchar](10) NOT NULL,
[ItemId] [varchar](20) NOT NULL,
[SizeId] [varchar](20) NOT NULL,
[SizeId2] [varchar](20) NOT NULL,
[ColorId] [varchar](20) NOT NULL,
[MatlPropId] [varchar](8) NOT NULL,
[LineNum] [tinyint] NOT NULL,
[SubForLineNum] [tinyint] NOT NULL,
[SerialNum] [varchar](20) NOT NULL,
[PalletNum] [varchar](20) NOT NULL,
[BatchNum] [varchar](20) NOT NULL,
[PQty] [numeric](28, 12) NOT NULL,
[PUnit] [varchar](10) NOT NULL,
[SQty] [numeric](28, 12) NOT NULL,
[SUnit] [varchar](10) NOT NULL,
[TQty] [numeric](28, 12) NOT NULL,
[TUnit] [varchar](10) NOT NULL,
[StkQty] [numeric](28, 12) NOT NULL,
[StkUnit] [varchar](10) NOT NULL,
[FtQty] [numeric](28, 12) NOT NULL,
[LbQty] [numeric](28, 12) NOT NULL,
[MQty] [numeric](28, 12) NOT NULL,
[KgQty] [numeric](28, 12) NOT NULL,
[Yield] [numeric](28, 12) NOT NULL,
[YieldUnit] [varchar](10) NOT NULL,
[WPQty] [numeric](28, 12) NOT NULL,
[WPUnit] [varchar](10) NOT NULL,
[WSQty] [numeric](28, 12) NOT NULL,
[WSUnit] [varchar](10) NOT NULL,
[SetNum] [int] NOT NULL,
[LaneNum] [tinyint] NOT NULL,
[RowNum] [smallint] NOT NULL,
[TranType] [varchar](10) NOT NULL,
[WasteId] [varchar](10) NOT NULL,
[Shift] [varchar](10) NOT NULL,
[ShiftTime] [datetime] NOT NULL,
[ShiftDate] [datetime] NOT NULL,
[PRGCode] [varchar](10) NOT NULL,
[UserRemark] [text] NOT NULL,
[JobType] [varchar](10) NOT NULL,
[WareHouseId] [varchar](10) NOT NULL,
[LocationId] [varchar](10) NOT NULL,
[AppUpdated] [tinyint] NOT NULL,
[OnOffUpdated] [tinyint] NOT NULL,
[InventTransId] [varchar](20) NOT NULL,
[OrgSerialNum] [varchar](100) NOT NULL,
[ReworkFlag] [tinyint] NOT NULL,
[Reworked] [tinyint] NOT NULL,
[Category] [varchar](50) NOT NULL,
[GroupTranNum] [varchar](10) NOT NULL,
[SystemCreated] [tinyint] NOT NULL,
[OfflineTran] [tinyint] NOT NULL,
[UpdLock] [tinyint] NOT NULL,
[UpdLockTime] [datetime] NOT NULL,
[SFBOMRevision] [int] NOT NULL,
[UDF01] [varchar](50) NOT NULL,
[UDF02] [varchar](50) NOT NULL,
[AddEdit] [tinyint] NOT NULL,
[CalcGauge] [numeric](28, 12) NOT NULL,
[MasterSerial] [varchar](100) NOT NULL,
[OprSerialCount] [smallint] NOT NULL,
[QACheck] [tinyint] NOT NULL,
[SpliceCount] [tinyint] NOT NULL,
[NumAcross] [tinyint] NOT NULL,
[PermitNum] [int] NOT NULL,
[TransAs] [char](1) NOT NULL,
[CreateTime] [datetime] NOT NULL,
[ModifyTime] [datetime] NOT NULL,
[OSUser] [varchar](20) NOT NULL,
[ComputerName] [varchar](40) NOT NULL,
[Reassign] [tinyint] NOT NULL,
[Reassigned] [tinyint] NOT NULL,
[OprCode] [varchar](10) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[SFMatl] Script Date: 20/04/2017 14:40:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SFMatl](
[RecId] [int] IDENTITY(1,1) NOT NULL,
[CompanyId] [char](3) NOT NULL,
[PrOdId] [varchar](10) NOT NULL,
[OprNum] [tinyint] NOT NULL,
[WrkCtrId] [varchar](10) NOT NULL,
[ItemId] [varchar](20) NOT NULL,
[SizeId] [varchar](20) NOT NULL,
[SizeId2] [varchar](20) NOT NULL,
[ColorId] [varchar](20) NOT NULL,
[MatlPropId] [varchar](8) NOT NULL,
[LineNum] [tinyint] NOT NULL,
[SubForLineNum] [tinyint] NOT NULL,
[SerialNum] [varchar](20) NOT NULL,
[PalletNum] [varchar](20) NOT NULL,
[BatchNum] [varchar](20) NOT NULL,
[PQty] [numeric](28, 12) NOT NULL,
[PUnit] [varchar](10) NOT NULL,
[SQty] [numeric](28, 12) NOT NULL,
[SUnit] [varchar](10) NOT NULL,
[TQty] [numeric](28, 12) NOT NULL,
[TUnit] [varchar](10) NOT NULL,
[StkQty] [numeric](28, 12) NOT NULL,
[StkUnit] [varchar](10) NOT NULL,
[FtQty] [numeric](28, 12) NOT NULL,
[LbQty] [numeric](28, 12) NOT NULL,
[MQty] [numeric](28, 12) NOT NULL,
[KgQty] [numeric](28, 12) NOT NULL,
[Yield] [numeric](28, 12) NOT NULL,
[YieldUnit] [varchar](10) NOT NULL,
[WPQty] [numeric](28, 12) NOT NULL,
[WPUnit] [varchar](10) NOT NULL,
[WSQty] [numeric](28, 12) NOT NULL,
[WSUnit] [varchar](10) NOT NULL,
[SetNum] [int] NOT NULL,
[LaneNum] [tinyint] NOT NULL,
[RowNum] [smallint] NOT NULL,
[TranType] [varchar](10) NOT NULL,
[WasteId] [varchar](10) NOT NULL,
[Shift] [varchar](10) NOT NULL,
[ShiftTime] [datetime] NOT NULL,
[ShiftDate] [datetime] NOT NULL,
[PRGCode] [varchar](10) NOT NULL,
[UserRemark] [text] NOT NULL,
[JobType] [varchar](10) NOT NULL,
[WareHouseId] [varchar](10) NOT NULL,
[LocationId] [varchar](10) NOT NULL,
[AppUpdated] [tinyint] NOT NULL,
[OnOffUpdated] [tinyint] NOT NULL,
[InventTransId] [varchar](20) NOT NULL,
[OrgSerialNum] [varchar](100) NOT NULL,
[ReworkFlag] [tinyint] NOT NULL,
[Reworked] [tinyint] NOT NULL,
[Category] [varchar](50) NOT NULL,
[GroupTranNum] [varchar](10) NOT NULL,
[SystemCreated] [tinyint] NOT NULL,
[OfflineTran] [tinyint] NOT NULL,
[UpdLock] [tinyint] NOT NULL,
[UpdLockTime] [datetime] NOT NULL,
[SFBOMRevision] [int] NOT NULL,
[UDF01] [varchar](50) NOT NULL,
[UDF02] [varchar](50) NOT NULL,
[AddEdit] [tinyint] NOT NULL,
[CalcGauge] [numeric](28, 12) NOT NULL,
[MasterSerial] [varchar](100) NOT NULL,
[OprSerialCount] [smallint] NOT NULL,
[QACheck] [tinyint] NOT NULL,
[SpliceCount] [tinyint] NOT NULL,
[NumAcross] [tinyint] NOT NULL,
[PermitNum] [int] NOT NULL,
[TransAs] [char](1) NOT NULL,
[CreateTime] [datetime] NOT NULL,
[ModifyTime] [datetime] NOT NULL,
[OSUser] [varchar](20) NOT NULL,
[ComputerName] [varchar](40) NOT NULL,
[Reassign] [tinyint] NOT NULL,
[Reassigned] [tinyint] NOT NULL,
[OprCode] [varchar](10) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
The main difference with those queries is they are not the same.
The table SELECTed is not the same.
This means two things in term of Query Plan.
Different statistics due to different amount of datas for example.
Different indexes or index fragmentation.
You can check indexes and their fragmentation (and maybe rebuild/reorganize them if required), you can also recalculate the statistics.
If it still keeps the same query plans,
then the difference is mainly due to data contained in the tables.
one of the main parameter ,sql server uses while creating a plan is statistics.So even if the data is same in both the tables you have ,statistics will be different,which leads to different execution plans
To view statistics for the tables ,you can use below
dbcc show_statistics('SFMatl','AppUpdated')
dbcc show_statistics('SFMatl','SFMatl_Backup20042017')
If you now,how to infer the above results, you will be able to see ,statistics are different for the above two tables ,which further decides plan quality

Mssql old table to new table different data types and empties

I have a new table I created for a membership application for a local club, anyway there existing software stored info in a DBF file I can import this into mssql as a table that's no trouble I am just stuck on merging the old data into the new table.
This is the old Table Structure (From DBF imported into mssql)
[NUMBER] [int] NULL,
[LASTNAME] [char](30) NULL,
[FIRSTNAME] [char](20) NULL,
[TITLE] [char](5) NULL,
[SALUTATION] [char](25) NULL,
[ADD1] [char](30) NULL,
[ADD2] [char](30) NULL,
[ADD3] [char](30) NULL,
[TOWN] [char](30) NULL,
[COUNTY] [char](30) NULL,
[POSTCODE] [char](8) NULL,
[TELEPHONE] [char](30) NULL,
[TYPE] [char](1) NULL,
[PAID] [char](1) NULL,
[COMMITTEE] [char](30) NULL,
[WARNINGS] [int] NULL,
[MONTHDRAW] [int] NULL,
[WOMANS] [char](1) NULL,
[SENIORCIT] [char](1) NULL,
[DOB] [datetime] NULL,
[AMOUNTCLUB] [decimal](6, 2) NULL,
[DATEPAY] [datetime] NULL,
[AMOUNTBRAN] [decimal](6, 2) NULL,
[AMOUNTDUE] [decimal](6, 2) NULL
This is the new Table:
[MemberID] [nvarchar](10) NOT NULL,
[Title] [nvarchar](10) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[Surname] [nvarchar](50) NOT NULL,
[HouseNumber] [nvarchar](25) NULL,
[Street] [nvarchar](25) NULL,
[City] [nvarchar](25) NULL,
[County] [nvarchar](25) NULL,
[Postcode] [nvarchar](10) NULL,
[TelephoneNumber] [nvarchar](15) NULL,
[MobileNumber] [nvarchar](15) NULL,
[EmailAddress] [nvarchar](50) NULL,
[DOB] [date] NULL,
[Age] [nvarchar](10) NULL,
[SeniorCitizen] [nvarchar](5) NULL,
[Warnings] [nvarchar](50) NULL,
[MembershipCategory] [nvarchar](20) NULL,
[ServiceBranch] [nvarchar](20) NULL,
[Paid] [nvarchar](10) NULL,
[ToPay] [float] NULL,
[DatePaidIn] [date] NULL,
[Entry] [tinyint] NULL,
[FOB] [nvarchar](10) NULL,
[JoinDate] [date] NULL,
[SubscriptionYear] [date] NULL,
[TotalPaid] [float] NULL,
I am writing the insert like;
INSERT INTO [dbo].[MemberDetails]
([MemberID],[Title],[FirstName],[Surname],[HouseNumber],[Street],[City],[County],[Postcode],[TelephoneNumber],[MobileNumber],[EmailAddress],[DOB],[Age],[SeniorCitizen],[Warnings],[MembershipCategory],[ServiceBranch],[Paid],[ToPay],[DatePaidIn],[Entry],[FOB],[JoinDate],[SubscriptionYear],[TotalPaid])
SELECT [NUMBER], [TITLE], [FIRSTNAME], [LASTNAME], [ADD1], [ADD2], [TOWN], [COUNTY], [POSTCODE], [TELEPHONE]
FROM [dbo].[MEMBERS]
GO
I got as far as that column then realized "how do I do empty values as no one in the old table had a mobile record?" also do I need to do Select AS "new column name" for the old table values?
Suppose you go from OldTable to NewTable, adding an answer column to the original question column:
insert NewTable
(question, answer)
select question
, '42' -- Specify a literal or default value
from OldTable
You can also omit the new column from the insert list:
insert NewTable
(question)
select question
from OldTable
This will copy the question column and put the default value null in the answer column.
You do not have to use aliases in the select list. It's strictly order based. This would work fine:
insert NewTable
(question)
select question as CeciNEstPasUnePipe
from OldTable

Can someone break down a PIVOT query for me please?

I am looking to pivot this data so the output can count how many people are in each age band...
Below is what I have done, but I don't even think I'm close....
I am using SQL Server 2008
SELECT [OA_Code], Dominant_F_Age, Age_F_90plus, Age_F_85_89, Age_F_80_84, Age_F_75_79, Age_F_70_74, Age_F_65_69, Age_F_60_64,
Age_F_55_59, Age_F_50_54, Age_F_45_49, Age_F_40_44, Age_F_35_39, Age_F_30_34, Age_F_25_29, Age_F_20_24, Age_F_15_19, Age_F_10_14, Age_F_5_9,
Age_F_0_4, Age_2001_F
FROM cen.AgeByGenderOA
PIVOT (
f_Age_data
for [F_Age_Data] in (Age_F_90plus, Age_F_85_89, Age_F_80_84, Age_F_75_79, Age_F_70_74, Age_F_65_69, Age_F_60_64,
Age_F_55_59, Age_F_50_54, Age_F_45_49, Age_F_40_44, Age_F_35_39, Age_F_30_34, Age_F_25_29, Age_F_20_24, Age_F_15_19, Age_F_10_14, Age_F_5_9),
Age_F_0_4)
My table looks like so:
CREATE TABLE AgeByGenderOA(
[OA_Code] AS VARCHAR(50),
[Age_M_0_4] [varchar](50) NULL,
[Age_M_5_9] [varchar](50) NULL,
[Age_M_10_14] [varchar](50) NULL,
[Age_M_15_19] [varchar](50) NULL,
[Age_M_20_24] [varchar](50) NULL,
[Age_M_25_29] [varchar](50) NULL,
[Age_M_30_34] [varchar](50) NULL,
[Age_M_35_39] [varchar](50) NULL,
[Age_M_40_44] [varchar](50) NULL,
[Age_M_45_49] [varchar](50) NULL,
[Age_M_50_54] [varchar](50) NULL,
[Age_M_55_59] [varchar](50) NULL,
[Age_M_60_64] [varchar](50) NULL,
[Age_M_65_69] [varchar](50) NULL,
[Age_M_70_74] [varchar](50) NULL,
[Age_M_75_79] [varchar](50) NULL,
[Age_M_80_84] [varchar](50) NULL,
[Age_M_85_89] [varchar](50) NULL,
[Age_M_90plus] [varchar](50) NULL,
[Dominant_M_Age] [varchar](50) NULL,
[Age_2001_F] [varchar](50) NULL,
[Age_F_0_4] [varchar](50) NULL,
[Age_F_5_9] [varchar](50) NULL,
[Age_F_10_14] [varchar](50) NULL,
[Age_F_15_19] [varchar](50) NULL,
[Age_F_20_24] [varchar](50) NULL,
[Age_F_25_29] [varchar](50) NULL,
[Age_F_30_34] [varchar](50) NULL,
[Age_F_35_39] [varchar](50) NULL,
[Age_F_40_44] [varchar](50) NULL,
[Age_F_45_49] [varchar](50) NULL,
[Age_F_50_54] [varchar](50) NULL,
[Age_F_55_59] [varchar](50) NULL,
[Age_F_60_64] [varchar](50) NULL,
[Age_F_65_69] [varchar](50) NULL,
[Age_F_70_74] [varchar](50) NULL,
[Age_F_75_79] [varchar](50) NULL,
[Age_F_80_84] [varchar](50) NULL,
[Age_F_85_89] [varchar](50) NULL,
[Age_F_90plus] [varchar](50) NULL,
[Dominant_F_Age] [varchar](50) NULL,
[MAPINFO_ID] [varchar](50) NULL)
As you can see it's a huge table. The "Age_M_0_4" columns are populated with numbers.
I would like my output to read
OA_Code, Age, countOfAge
123456, Age_0_4, 26
123456, Age_5_9, 24
789456, Age_0_4, 10
789456, Age_5_9, 12
This would be inclusive of male and female ages.
Anyone fancy taking a crack at this one?
Finally: The data contained in the "Age_M_" Columns is all numbers counts. 50, 40, 2, 0 etc...
You do not want a PIVOT, you need to UNPIVOT the data. Since you are using SQL Server 2008+, you can use CROSS APPLY with a VALUES clause. The code will be similar to this:
select t.OA_Code,
c.age,
sum(cast(c.value as int)) countOfAge
from AgeByGenderOA t
cross apply
(
values
('Age_0_4', Age_M_0_4),
('Age_5_9', Age_M_5_9),
('Age_10_14', Age_M_10_14),
('Age_15_19', Age_M_15_19) ... add the other columns here
) c (age, value)
group by t.OA_Code, c.age
See SQL Fiddle with Demo
Edit, If you want both Male/Female columns you will include ALL of the columns in the values clause, but give them the same age range value:
select t.OA_Code,
c.age,
sum(cast(c.value as int)) countOfAge
from AgeByGenderOA t
cross apply
(
values
('Age_0_4', Age_M_0_4),
('Age_5_9', Age_M_5_9),
('Age_10_14', Age_M_10_14),
('Age_15_19', Age_M_15_19),
('Age_0_4', Age_F_0_4),
('Age_5_9', Age_F_5_9),
('Age_10_14', Age_F_10_14),
('Age_15_19', Age_F_15_19)
) c (age, value)
group by t.OA_Code, c.age;
See SQL Fiddle with Demo