Creating a new SQL Server table from an existing table - sql

I have the job of updating a database table by removing the month column and recreating that table grouping on column fields and summing the hours column.
Here are my instructions: "Create a new PS_StaffHours table without the Month column. Migrate the existing PS_StaffHours data to the new table by grouping on (PSScnID/PSEmpID/Prd/WBSID/RatePrd) and summing the hours."
Now here is the table I scripted out and have to re-create without the Month column and summing the hour column:
CREATE TABLE [dbo].[PS_StaffHours]
(
[PSScnID] [int] NOT NULL,
[PSEmpID] [int] NOT NULL,
[Prd] [int] NOT NULL,
[WBSID] [int] NOT NULL,
[RatePrd] [int] NOT NULL,
[Month] [date] NOT NULL,
[Hours] [decimal](16, 8) NOT NULL,
CONSTRAINT [PK_PS_StaffHours]
PRIMARY KEY CLUSTERED ([PSScnID] ASC, [PSEmpID] ASC, [Prd] ASC,
[WBSID] ASC, [RatePrd] ASC, [Month] 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
ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK
ADD CONSTRAINT [FK_PS_StaffHours_PS_Scenarios]
FOREIGN KEY([PSScnID]) REFERENCES [dbo].[PS_Scenarios] ([PSScnID])
GO
ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [FK_PS_StaffHours_PS_Scenarios]
GO
ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK
ADD CONSTRAINT [FK_PS_StaffHours_PS_Staff]
FOREIGN KEY([PSScnID], [PSEmpID]) REFERENCES [dbo].[PS_Staff] ([PSScnID], [PSEmpID])
GO
ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [FK_PS_StaffHours_PS_Staff]
GO
ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK
ADD CONSTRAINT [FK_PS_StaffHours_PS_WBS]
FOREIGN KEY([PSScnID], [WBSID]) REFERENCES [dbo].[PS_WBS] ([PSScnID], [WBSID])
GO
ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [FK_PS_StaffHours_PS_WBS]
GO
ALTER TABLE [dbo].[PS_StaffHours] WITH CHECK
ADD CONSTRAINT [CK_PS_StaffHours] CHECK ((DATEPART(day, [Month]) = (1)))
GO
ALTER TABLE [dbo].[PS_StaffHours] CHECK CONSTRAINT [CK_PS_StaffHours]
GO
EXEC sys.sp_addextendedproperty
#name = N'MS_Description',
#value = N'Restricts Month field to the 1st of every month.' ,
#level0type = N'SCHEMA', #level0name = N'dbo',
#level1type = N'TABLE', #level1name = N'PS_StaffHours',
#level2type = N'CONSTRAINT', #level2name = N'CK_PS_StaffHours'
GO
First, to create the new table I think all I have to do is rename the table name in the CREATE portion of the script and just remove all references of the Month column in the CREATE statement. Am I correct in my thinking about the CREATE script?
Now, here is the script I'm going to use to populate the table without the Month field but I'm not sure if I have the grouping correct because I am getting an error because I'm not grouping on the Hours column with the rest. Also, I'm unsure about how to go about summing the hours in the query.
My code:
SELECT c.PSScnID, c.PSEmpID, c.Prd, c.WBSID, c.RatePrd, c.Hours
INTO dbo.NewPS_StaffHours
FROM PS_StaffHours AS c
GROUP BY c.PSScnID, c.PSEmpID, c.Prd, c.WBSID, c.RatePrd
GO

Your first assumption is correct.
To group by your columns and sum up the hours - try this:
SELECT c.PSScnID, c.PSEmpID, c.Prd, c.WBSID, c.RatePrd, SUM(c.Hours) AS Hours
INTO dbo.NewPS_StaffHours
FROM PS_StaffHours AS c
GROUP BY c.PSScnID, c.PSEmpID, c.Prd, c.WBSID, c.RatePrd
GO
Sounds like you're going to be creating your table before running your select.
So get rid of the INTO dbo.NewPS_StaffHours. Run a create table statement and then and INSERT INTO newTable VALUES... SELECT

Related

SQL DLETE Statement not working

I have a customized application in my company where I can create a place for users to input their values to a database.
The table where I am submitting the data has 5 columns with its SQL CREATE Query as below:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Log_Ongoing](
[ID] [int] IDENTITY(1,1) NOT NULL,
[LogType] [int] NULL,
[ActivityDate] [datetime] NOT NULL,
[ActivityDescription] [text] NULL,
[Train] [int] NULL,
CONSTRAINT [PK_Log_Ongoing] 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] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Log_Ongoing] WITH CHECK ADD CONSTRAINT [FK_Log_Ongoing_Trains] FOREIGN KEY([Train])
REFERENCES [dbo].[Trains] ([Id])
GO
ALTER TABLE [dbo].[Log_Ongoing] CHECK CONSTRAINT [FK_Log_Ongoing_Trains]
GO
The purpose of this table is to record the ongoing activities in the plant.
The user can come later and modify those activities by updating, adding or deleting through the application by choosing the report data then modifying the data.
My thinking was that before the user submits the data I will delete the old data with the same report date first then insert the new data again.
Unfortunately the data is submitted successfully, but not deleted.
I made a SQL trace to check the queries that the application sends to the database, and I found the below two statements:
exec sp_executesql N'DELETE FROM Log_Ongoing WHERE ActivityDate = #StartDate',N'#startDate datetimeoffset(7)',#startDate='2017-02-12 07:00:00 +02:00'
exec sp_executesql N'INSERT INTO Log_Ongoing (LogType, ActivityDate, ActivityDescription, Train ) VALUES (1,#StartDate, #Activity, #Train)',N'#Train int,#Activity nvarchar(2),#startDate datetimeoffset(7)',#Train=1,#Activity=N'11',#startDate='2017-02-12 07:00:00 +02:00'
When I tested the INSERT staement in the SSMS, it worked fine, but then when I tested the DELETE statement, it didn't work. What is wrong with this query?

Understanding creating simple stored procedures

I'm in the process of learning to create stored procedures in Microsoft SQL Server Management Studio. I need to create a stored procedure that adds a single new record to my table. Also, I need to create two extra output parameters along with the stored procedure (I chose ##error and SCOPE_IDENTITY()).
This is the code I use to create my stored procedure:
use bieren
go
if exists
(select name from sysobjects
where name = 'spBierInsert' and xtype = 'p')
drop procedure spBierInsert
go
create procedure spBierInsert
#Biernr int = 0,
#Naam nvarchar(100) = '',
#BrouwerNr int = 0,
#SoortNr int = 0,
#Alcohol real,
#gelukt nvarchar(10) output,
#id int output
as
begin
declare #fout int
insert into bieren
values (#Biernr, #Naam, #BrouwerNr, #SoortNr, #Alcohol)
set #fout = ##error
print 'Foutnummer:' + cast(#fout as varchar(4))
if #fout > 0
set #gelukt = 'Neen: ' + cast(#fout as varchar(4))
else
set #gelukt = 'Ja'
set #id = SCOPE_IDENTITY()
end
I must be doing something wrong, because the result is the following:
Msg 547, Level 16, State 0, Procedure spBierInsert, Line 92
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Bieren_Brouwers". The conflict occurred in database "Bieren", table
"dbo.Brouwers", column 'BrouwerNr'.
The statement has been terminated.
Foutnummer:547
(1 row(s) affected)
What have I done incorrectly?
EDIT 30/12/2015: I have updated this question with new information. I originally just used terms like "exampletable" because I had no idea that the search to the answer to my question would be more involved than a single answer, so I've gone ahead and changed the entire code above (as well as the text for the error), and I've added the script for my table underneath. The point of this question is that I come out with code that works, or, that I at least understand what's wrong with it.
USE [Bieren]
GO
/****** Object: Table [dbo].[Bieren] Script Date: 30/12/2015 0:19:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Bieren](
[BierNr] [int] NOT NULL,
[Naam] [nvarchar](100) NULL,
[BrouwerNr] [int] NULL,
[SoortNr] [int] NULL,
[Alcohol] [real] NULL,
CONSTRAINT [PK_Bieren] PRIMARY KEY CLUSTERED
(
[BierNr] 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
ALTER TABLE [dbo].[Bieren] WITH CHECK ADD CONSTRAINT [FK_Bieren_Brouwers] FOREIGN KEY([BrouwerNr])
REFERENCES [dbo].[Brouwers] ([BrouwerNr])
GO
ALTER TABLE [dbo].[Bieren] CHECK CONSTRAINT [FK_Bieren_Brouwers]
GO
ALTER TABLE [dbo].[Bieren] WITH CHECK ADD CONSTRAINT [FK_Bieren_Soorten] FOREIGN KEY([SoortNr])
REFERENCES [dbo].[Soorten] ([SoortNr])
GO
ALTER TABLE [dbo].[Bieren] CHECK CONSTRAINT [FK_Bieren_Soorten]
GO
Your procedure is created fine. The problem is that you are inserting a value in column 'BrouwerNr' of table "dbo.Brouwers" which doesn't exist in "SoortNr" column of table "dbo.Soorten". There is foreign set on the table "dbo.Brouwers" named "[FK_Bieren_Soorten]" which is causing this restriction. I suggest you look into this article to know more about foreign keys.
The error is because you are inserting 1600 in #ColumnNr, which is a foreign key of another table and does not have 1600 in it.
You can do the following :
right click on "exampletable" table and select 'Script table as'->'Create to'->'new query editor window'
Now,find "ColumnNr" in it. It will be something like this =>
ALTER TABLE [dbo].[exampleTable] WITH CHECK ADD CONSTRAINT [FK_exampleTable_**OtherTableName**_ColumnNr] FOREIGN KEY([ColumnNr])
REFERENCES [dbo].**[OtherTableName]** ([ColumnNr])
GO
Now open the mentioned table "OtherTableName" in the query and look for the column "ColumnNr". It will not be having value 1600.
Try to insert any value in
#ColumnNr = {//Any value from **OtherTableName**},
which is in table "OtherTableName"

why this insert statement cannot insert values in it's second iteration?

I have this reasonably sized stored procedure that accepts 3 collections two UDTT collection and one CSV collection.
I have passed the following values to test stored procedure. However the problems occurred in one small master table called EmpDesignations with 5 columns. There is a loop I used in the store procedure to insert values to EmpDesignations. The loop is required because the values are extracted from the CSV string. As expected it does iterate 2 times with two sets of values. The first iteration the data was inserted successfully but in the second iteration data was not inserted. I have checked weather the data is empty but those variables #tmpEmpID and #tmp contain data. So cannot figure out the problem
The EmpDesignations table definition is
EmpID PK, FK not null
DesigID PK, FK not null
IsValid int not null
UpdtDT datetime not null containts to getDate()
AuthID int not null  EmpID
here is the snapshot of the table columns and types
In the first iteration the passing values to the insert statement is shown in the watch window
As you can see, ##rowcount is 1 so worked in the first round!
In the following watch shows the passing values to the insert statement, this is in the second iteration:
But the ##rowcount is not 1 therefore the control rollbacks all insertions
Here is a video link of the debugging of the insert statement
here is the video of THE SECOND INSERT statement debugging
Table definition is correct, the number of values passed matches the number of input columns, and the variables are filled with values in both iterations, so what could be the problem???
here is the script that was generated by SQL server for the table EmpDesignations
USE [SMSV100]
GO
/****** Object: Table [dbo].[EmpDesignations] Script Date: 04/12/2014 08:50:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmpDesignations](
[EmpID] [int] NOT NULL,
[DesigID] [int] NOT NULL,
[IsValid] [int] NOT NULL,
[UpdtDT] [datetime] NOT NULL,
[AuthID] [int] NOT NULL,
CONSTRAINT [PK_EmpDesignations] PRIMARY KEY CLUSTERED
(
[EmpID] ASC,
[DesigID] 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
ALTER TABLE [dbo].[EmpDesignations] WITH CHECK ADD CONSTRAINT [FK_EmpDesignations_Designations] FOREIGN KEY([DesigID])
REFERENCES [dbo].[Designations] ([DesigID])
GO
ALTER TABLE [dbo].[EmpDesignations] CHECK CONSTRAINT [FK_EmpDesignations_Designations]
GO
ALTER TABLE [dbo].[EmpDesignations] WITH CHECK ADD CONSTRAINT [FK_EmpDesignations_Employees] FOREIGN KEY([EmpID])
REFERENCES [dbo].[Employees] ([EmpID])
GO
ALTER TABLE [dbo].[EmpDesignations] CHECK CONSTRAINT [FK_EmpDesignations_Employees]
GO
ALTER TABLE [dbo].[EmpDesignations] ADD CONSTRAINT [DF_EmpDesignations_UpdtDT] DEFAULT (getdate()) FOR [UpdtDT]
GO
thanks

Create Table if not exists without columns

Is it possible to just create a table in MSSQL without columns?
I'm asking this because I'll have to check for every columns if it already exists or not.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].Tags(
[Id] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_Tags] 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]
END
GO
The execution might break by creating the column Id if the table and the column already exists.
This would be ideally:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U'))
CREATE TABLE [dbo].Tags
GO
if NOT EXISTS (select column_name from INFORMATION_SCHEMA.columns where table_name = 'Tags' and column_name = 'Id')
alter table MyTable add MyColumn int IDENTITY(1,1) NOT NULL
GO
-- add new primary key constraint on new column
ALTER TABLE dbo.Tags
ADD CONSTRAINT PK_Tags
PRIMARY KEY CLUSTERED ([Id] ASC)
GO
I can't find an example on the second piece of code. But I can imagine that a table can't be created with 0 columns.
Any suggestions?
[Edit]
Some more context. Some tables exists some don't. Some columns exists some don't. I want to creat a script which could be executed anytime without breaking or causing error msg's like the table/column already exists.
This code
create table tab
raises an error
Incorrect syntax near 'tab'.
and this code
create table tab1
(
id int
)
alter table tab1 drop id
raises an error
ALTER TABLE 'tab1' failed. Dropping all columns in a table is not
allowed.
so a table without columns is not possible.
I think you can acheive what you're trying using the following:
Create the table with the ID and only check for the existence of the Id column if you didn't have to create the table.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tags]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].Tags (Id int IDENTITY(1,1) NOT NULL)
END
ELSE
BEGIN
if NOT EXISTS (select column_name from INFORMATION_SCHEMA.columns where table_name = 'Tags' and column_name = 'Id')
BEGIN
alter table [dbo].Tags add MyColumn int IDENTITY(1,1) NOT NULL
-- add new primary key constraint on new column
ALTER TABLE dbo.Tags
ADD CONSTRAINT PK_Tags
PRIMARY KEY CLUSTERED ([Id] ASC)
END
ELSE
GO
Of course you can't create table without columns in SQL Server, but if the table doesn't exist before you create it, it doesn't have any column, so why don't you simply create it?
If this is a kind of upgrade script you might do an ELSE branch where you check for each column before adding it.

Alter Table Add Column Syntax

I'm trying to programmatically add an identity column to a table Employees. Not sure what I'm doing wrong with my syntax.
ALTER TABLE Employees
ADD COLUMN EmployeeID int NOT NULL IDENTITY (1, 1)
ALTER TABLE Employees ADD CONSTRAINT
PK_Employees PRIMARY KEY CLUSTERED
(
EmployeeID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
What am I doing wrong? I tried to export the script, but SQL Mgmt Studio does a whole Temp Table rename thing.
UPDATE:
I think it is choking on the first statement with "Incorrect syntax near the keyword 'COLUMN'."
Just remove COLUMN from ADD COLUMN
ALTER TABLE Employees
ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)
ALTER TABLE Employees ADD CONSTRAINT
PK_Employees PRIMARY KEY CLUSTERED
(
EmployeeID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
This is how Adding new column to Table
ALTER TABLE [tableName]
ADD ColumnName Datatype
E.g
ALTER TABLE [Emp]
ADD Sr_No Int
And If you want to make it auto incremented
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
The correct syntax for adding column into table is:
ALTER TABLE table_name
ADD column_name column-definition;
In your case it will be:
ALTER TABLE Employees
ADD EmployeeID int NOT NULL IDENTITY (1, 1)
To add multiple columns use brackets:
ALTER TABLE table_name
ADD (column_1 column-definition,
column_2 column-definition,
...
column_n column_definition);
COLUMN keyword in SQL SERVER is used only for altering:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
It could be doing the temp table renaming if you are trying to add a column to the beginning of the table (as this is easier than altering the order). Also, if there is data in the Employees table, it has to do insert select * so it can calculate the EmployeeID.