Could not select additional column names if dropped temporary table is created again with additional column names - sql

Though I have dropped the temporary table, it does not let me select the new column names if the temporary table with same table name with additional column names will be created.
I have been using SQL Server 2008.
Try this code for instance:
IF (object_id('tempdb..#xyz') IS NOT NULL)
DROP TABLE #xyz;
CREATE TABLE #xyz(
[a] [datetime] NULL,
[b] [nvarchar](255) NULL,
[c] [nvarchar](255) NULL
) ON [PRIMARY]
GO
IF (object_id('tempdb..#xyz') IS NOT NULL)
DROP TABLE #xyz;
CREATE TABLE #xyz(
[a] [datetime] NULL,
[b] [nvarchar](255) NULL,
[c] [nvarchar](255) NULL,
[d] [nvarchar](255) NULL
) ON [PRIMARY]
SELECT [d] FROM #xyz
This says:
Msg 207, Level 16, State 1, Line 13
Invalid column name 'd'.
Again, if we try like selecting * as mentioned by Martin Parkin, it gives result with column name d.
I could not select * for my dynamic columns and it doesn't let me to select additional columns.
Why?
Fiddle

You need GO to separate DROP and CREATE statements. They need to be in separate batches.
IF (object_id('tempdb..#xyz') IS NOT NULL)
DROP TABLE #xyz;
CREATE TABLE #xyz(
[a] [datetime] NULL,
[b] [nvarchar](255) NULL,
[c] [nvarchar](255) NULL
) ON [PRIMARY]
GO
IF (object_id('tempdb..#xyz') IS NOT NULL)
DROP TABLE #xyz;
GO
CREATE TABLE #xyz(
[a] [datetime] NULL,
[b] [nvarchar](255) NULL,
[c] [nvarchar](255) NULL,
[d] [nvarchar](255) NULL
) ON [PRIMARY]
SELECT [d] FROM #xyz

Related

T-SQL split table vertically (moving column) with (almost) same performance

In T-SQL (MS SQL Server 2016) I want to split vertically a big table (220 GB - 500 million rows) as some columns data are descriptions and some are daily data.
So from
CREATE TABLE [BigTable](
[OptionID] [int] NOT NULL,
[Date] [datetime] NOT NULL,
[ParentID] [bigint] NOT NULL,
[Description] [char](255) NOT NULL,
[Price] [real] NULL,
[PriceTheo] [real] NULL
CONSTRAINT [PK_BigTable] PRIMARY KEY CLUSTERED
(
[ParentID] ASC,
[Date] ASC,
[OptionID] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
I would move to:
CREATE TABLE [DescriptionTable](
[OptionVersionID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[OptionID] [int] NOT NULL,
[ParentID] [bigint] NOT NULL,
[Description] [char](255) NOT NULL,
CONSTRAINT [PK_DescriptionTable] PRIMARY KEY CLUSTERED
([OptionVersionID] ASC) ON [PRIMARY]) ON [PRIMARY]
CREATE TABLE [DailyTable](
[OptionVersionID] [int] NOT NULL,
[Date] [datetime] NOT NULL,
[Price] [real] NULL,
[PriceTheo] [real] NULL
CONSTRAINT [PK_DailyTable] PRIMARY KEY CLUSTERED
([OptionVersionID] ASC,[Date] ASC) ON [PRIMARY]) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_DailyTable_Date] ON [DailyTable]
([Date] ASC) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_DailyTable_OptionVersionID] ON [DailyTable]
([OptionVersionID] ASC) ON [PRIMARY]
GO
ALTER TABLE [DailyTable] WITH CHECK ADD CONSTRAINT [FK_DailyTable_DescriptionTable] FOREIGN KEY([OptionVersionID])
REFERENCES [DescriptionTable] ([OptionVersionID])
GO
ALTER TABLE [DailyTable] CHECK CONSTRAINT [FK_DailyTable_DescriptionTable]
GO
I then create a view
CREATE VIEW [vBigTable]
AS
SELECT
[OptionID],
[Date],
[ParentID],
[Description],
[Price],
[PriceTheo]
FROM DailyTable da INNER JOIN
DescriptionTable de ON da.OptionVersionID = de.OptionVersionID
I thought I should get the same kind of performance (almost) when I request data from the view vBigTable but actually I don't (some request can be 10x slower). Do I miss something to have almost the same performance when I select, join, group by ... (only reading data) from vBigTable or even when I use the specific INNER JOIN between Description and Daily table?
PS: I have more non clustered indices and columns in real life.

SQL Server: select records, not linked to another table

I have a table:
CREATE TABLE [dbo].[CollectionSite]
(
[SiteCode] [nvarchar](32) NOT NULL,
[AddressId] [int] NOT NULL,
[RemittanceId] [int] NULL,
// additional columns
)
and a linked table:
CREATE TABLE [dbo].[CollectionSiteAddress]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NULL,
[Address1] [nvarchar](255) NULL,
[Address2] [nvarchar](255) NULL,
[City] [nvarchar](128) NULL,
[State] [nvarchar](64) NULL,
[Zip] [nvarchar](32) NULL,
)
Relationship between these 2 tables:
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_AddressId]
FOREIGN KEY([AddressId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_RemittanceId]
FOREIGN KEY([RemittanceId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
I want to select all records from CollectionSiteAddress, which are not linked to CollectionSite (neither AddressId nor RemittanceId). Which request should I use?
I tried:
SELECT *
FROM CollectionSiteAddress
LEFT JOIN CollectionSite ON CollectionSiteAddress.Id = CollectionSite.AddressId
OR CollectionSiteAddress.Id = CollectionSite.RemittanceId
but it selects all records from CollectionSiteAddress
You are missing this WHERE clause:
WHERE CollectionSite.[SiteCode] IS NULL
because you want all the unmatched rows of CollectionSiteAddress.
I used the column [SiteCode] to check if it is NULL because it is not nullable in the definition of the table.
So you can write your query like this (shortened with aliases):
SELECT csa.*
FROM CollectionSiteAddress csa LEFT JOIN CollectionSite cs
ON csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
WHERE cs.[SiteCode] IS NULL
Or use NOT EXISTS:
SELECT csa.*
FROM CollectionSiteAddress csa
WHERE NOT EXISTS (
SELECT 1
FROM CollectionSite cs
WHERE csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
)

SQL Query to update a colums from a table base on a datetime field

I have 2 table called tblSetting and tblPaquets.
I need to update 3 fields of tblPaquets from tblSetting base on a where clause that use a datetime field of tblPaquest and tblSetting.
The sql below is to represent what I am trying to do and I know it make no sense right now.
My Goal is to have One query to achieve this goal.
I need to extract the data from tblSettings like this
SELECT TOP(1) [SupplierID],[MillID],[GradeFamilyID] FROM [tblSettings]
WHERE [DateHeure] <= [tblPaquets].[DateHeure]
ORDER BY [DateHeure] DESC
And Update tblPaquets with this data
UPDATE [tblPaquets]
SET( [SupplierID] = PREVIOUS_SELECT.[SupplierID]
[MillID] = PREVIOUS_SELECT.[MillID]
[GradeFamilly] = PREVIOUS_SELECT.[GradeFamilyID] )
Here the table design
CREATE TABLE [tblSettings](
[ID] [int] NOT NULL,
[SupplierID] [int] NOT NULL,
[MillID] [int] NOT NULL,
[GradeID] [int] NOT NULL,
[TypeID] [int] NOT NULL,
[GradeFamilyID] [int] NOT NULL,
[DateHeure] [datetime] NOT NULL,
[PeakWetEnable] [tinyint] NULL)
CREATE TABLE [tblPaquets](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PaquetID] [int] NOT NULL,
[DateHeure] [datetime] NULL,
[BarreCode] [int] NULL,
[Grade] [tinyint] NULL,
[SupplierID] [int] NULL,
[MillID] [int] NULL,
[AutologSort] [tinyint] NULL,
[GradeFamilly] [int] NULL)
You can do this using CROSS APPLY:
UPDATE p
SET SupplierID = s.SupplierID,
MillID = s.MillID
GradeFamilly = s.GradeFamilyID
FROM tblPaquets p CROSS APPLY
(SELECT TOP (1) s.*
FROM tblSettings s
WHERE s.DateHeure <= p.DateHeure
ORDER BY p.DateHeure DESC
) s;
Notes:
There are no parentheses before SET.
I don't recommend using [ and ] to escape identifiers, unless they need to be escaped.
I presume the query on tblSettings should have an ORDER BY to get the most recent rows.

Why do i get this error when i do a SELECT..INSERT in SQL Server

Why do i get this error
The select list for the INSERT statement contains more items than the
insert list. The number of SELECT values must match the number of
INSERT columns.
When i run this query
INSERT INTO TempOutputOfGroupifySP
(MonthOfQuery,Associate,[NoOfClaims],[ActualNoOfLines],[AverageTATInDays],
[NoOfErrorsDiscovered],[VarianceinPercent],[NoOfClaimsAudited],[InternalQualInPercent],[ExternalQualInPercent]
)
SELECT (DATENAME(MONTH,[ClaimProcessedDate])) AS MonthOfQuery,
Temp.Associate AS Associate,
COUNT(*) AS [NoOfClaims],
SUM(NoOfLines) AS [ActualNoOfLines] ,
(SUM(DATEDIFF(dd,[ClaimReceivedDate],[ClaimProcessedDate]))/COUNT(*)) AS [AverageTATInDays],
A.[NoOfErrorsDiscovered] AS [NoOfErrorsDiscovered],
Temp.[MonthlyTarget] As [TargetNoOfLines],(Temp.[MonthlyTarget] - COUNT(*)) AS [VarianceInPercent],
B.[NoOfClaimsAudited] AS [NoOfClaimsAudited],
((A.[NoOfErrorsDiscovered]/NULLIF(B.[NoOfClaimsAudited],0))*100) AS [InternalQualInPercent],
NULL AS [ExternalQualInPercent]
FROM
(SELECT COUNT(*) AS [NoOfErrorsDiscovered] FROM TempTableForStatisticsOfAssociates T1 WHERE [TypeOfError] IS NOT NULL) AS A,
(SELECT COUNT(*) AS [NoOfClaimsAudited] FROM TempTableForStatisticsOfAssociates T2 WHERE Auditor IS NOT NULL) AS B,
TempTableForStatisticsOfAssociates Temp
GROUP BY DATENAME(MONTH,([ClaimProcessedDate])),
Temp.Associate,
A.[NoOfErrorsDiscovered],
Temp.[MonthlyTarget],
B.[NoOfClaimsAudited]
Strucuture of the target table is
CREATE TABLE [dbo].[TempOutputOfGroupifySP](
[MonthOfQuery] [nchar](10) NULL,
[Associate] [nvarchar](max) NULL,
[NoOfClaims] [int] NULL,
[ActualNoOfLines] [int] NULL,
[AverageTATInDays] [int] NULL,
[NoOfErrorsDiscovered] [int] NULL,
[VarianceInPercent] [float] NULL,
[NoOfClaimsAudited] [int] NULL,
[InternalQualInPercent] [float] NULL,
[ExternalQualInPercent] [float] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Your INSERT INTO defines 10 colums for the insertion, however, your SELECT statement return 11 columns. You are either missing a column in your INSERT statement or returning one too many in your SELECT statement.
Comparing your table structure and your SELECT and INSERT the following line in your SELECT statement doesn't have a counterpart:
Temp.[MonthlyTarget] As [TargetNoOfLines]

Select all rows from table having two given values anywhere in rows

I have a table of bus route. this table has fields like bus no. , route code , starting point , end point, and upto 10 halts from halt1 , halt2...halt10 . i have filled data in this table. now i want to select all rows having two values,for example jaipur and vasai. in my table, there are two rows that have jaipur and vasai. In one row, jaipur is in column halt2 and vasai in halt9. Similarly another row has jaipur in halt4 column and vasai in halt10 column.
please help me to find out sql query. I am using MS SQL server.
scrip
USE [JaipuBus]
GO
/****** Object: Table [dbo].[MyRoutes] Script Date: 02/24/2014 13:28:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MyRoutes](
[id] [int] IDENTITY(1,1) NOT NULL,
[Route_No] [nvarchar](50) NULL,
[Route_Code] [nvarchar](50) NULL,
[Color] [nvarchar](50) NULL,
[Start_Point] [nvarchar](200) NULL,
[End_Point] [nvarchar](200) NULL,
[halt1] [nvarchar](50) NULL,
[halt2] [nvarchar](50) NULL,
[halt3] [nvarchar](50) NULL,
[halt4] [nvarchar](50) NULL,
[halt5] [nvarchar](50) NULL,
[halt6] [nvarchar](50) NULL,
[halt7] [nvarchar](50) NULL,
[halt8] [nvarchar](50) NULL,
[halt9] [nvarchar](50) NULL,
[halt10] [nvarchar](50) NULL,
CONSTRAINT [PK_MyRoutes] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
use CONTAINS
SELECT *
WHERE CONTAINS((startingpoint,endpoint,halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10), 'jaipur')
AND CONTAINS((startingpoint,endpoint,halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10), 'vasai');
SELECT * FROM bus_rout WHERE (halt1='aaa' OR halt2='aaa' OR .... halt10='aaa') AND (halt1='bbb' OR halt2='bbb' OR ....... halt10='bbb')
The where clause could be generated by code.
Based on your input, it seems to be a necessity for you to have Normalized table structure.
CREATE TABLE [dbo].[MyRoutes](
[id] [int] IDENTITY(1,1) NOT NULL,
[Route_No] [nvarchar](50) NULL,
[Route_Code] [nvarchar](50) NULL,
[Color] [nvarchar](50) NULL,
[Start_Point] [nvarchar](200) NULL,
[End_Point] [nvarchar](200) NULL,
[HaltNum] INT,
[Halt] [nvarchar](50) NULL
)
Then a query to solve the routes problem can be written as below:
SELECT a.Route_No, a.Route_Code, a.Color, a.Start_Point, a.End_Point,
a.HaltNum StartNum, b.HaltNum StopNum
FROM MyRoutes a
INNER JOIN MyRoutes b
ON a.id = b.id
WHERE a.Halt = 'jaipur' AND b.Halt = 'vasai'
AND a.HaltNum < b.HaltNum
Even better design of the table structure would be to have a separate master table for all Stops where you can maintain only StopId and StopName. In the MyRoutes table then you can have HaltId as foreign key referencing StopId column of the all stops master table. The above query would then need to inner join with this table twice to have conditions on StopName