If statement - TSQL - sql-server

What I'm trying to achieve is to check if a table exists:
if it exists, just truncate it
if it does not exist, create the table
Below is my code but I get an error.
Code:
--Check if table exists
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Com_SQL_Server_Agent_Monitor]')
AND type in (N'U'))
TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE
--Create table if not exist
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
(
[job_id] [uniqueidentifier] NULL,
[originating_server] [nvarchar](30) NULL,
[name] [nvarchar](128) NULL,
[enabled] [tinyint] NULL,
[description] [nvarchar](512) NULL,
[start_step_id] [int] NULL,
[category] [nvarchar](128) NULL,
[owner] [nvarchar](128) NULL,
[notify_level_eventlog] [int] NULL,
[notify_level_email] [int] NULL,
[notify_level_netsend] [int] NULL,
[notify_level_page] [int] NULL,
[notify_email_operator] [nvarchar](128) NULL,
[notify_netsend_operator] [nvarchar](128) NULL,
[notify_page_operator] [nvarchar](128) NULL,
[delete_level] [int] NULL,
[date_created] [datetime] NULL,
[date_modified] [datetime] NULL,
[version_number] [int] NULL,
[last_run_date] [int] NULL,
[last_run_time] [int] NULL,
[last_run_outcome] [int] NULL,
[next_run_date] [int] NULL,
[next_run_time] [int] NULL,
[next_run_schedule_id] [int] NULL,
[current_execution_status] [int] NULL,
[current_execution_step] [nvarchar](128) NULL,
[current_retry_attempt] [int] NULL,
[has_step] [int] NULL,
[has_schedule] [int] NULL,
[has_target] [int] NULL,
[type] [int] NULL
) ON [PRIMARY]
GO
This is the error I get:
There is already an object named 'Com_SQL_Server_Agent_Monitor' in the database
Any ideas what I'm missing?

The biggest problem in your code is the fact that you have multiple SQL statements in your ELSE block - but they're not framed by a BEGIN ... END.
So really what you have right now is:
IF EXISTS (....)
TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE
SET ANSI_NULLS ON
-- these statements will be executed ALWAYS - no matter what the
-- IF EXISTS() check returns!
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
......
So even if the table exists, and gets truncated - the SET QUOTED_IDENTIFIER ON and the CREATE TABLE statement will still be executed! That's why you're getting an error "table already exists".
What you need to do is:
IF EXISTS (....)
TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE
BEGIN
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
......
END

Related

SQL Server DELETE query performance

I've got a simple table and I'm evaluating which is the best way to delete some records from it.
The DELETE query is so simple: DELETE FROM [dbo].[Badge] WHERE [Id_Operatore] = #SOMEVALUE
Is there a way to increase performance of this operation?
This is the table:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Badge](
[Id_Badge] [int] IDENTITY(1,1) NOT NULL,
[Id_Operatore] [int] NULL,
[Badge0] [smallint] NULL,
[Badge1] [smallint] NULL,
[Badge2] [smallint] NULL,
[Badge3] [smallint] NULL,
[Badge4] [smallint] NULL,
[Badge5] [smallint] NULL,
[Badge6] [smallint] NULL,
[Badge7] [smallint] NULL,
[Badge8] [smallint] NULL,
[Badge9] [smallint] NULL,
[Badge10] [smallint] NULL,
[Badge11] [smallint] NULL,
[Badge12] [smallint] NULL,
[Badge13] [smallint] NULL,
[Badge14] [smallint] NULL,
[Badge15] [smallint] NULL,
[Badge16] [smallint] NULL,
[Badge17] [smallint] NULL,
[Badge18] [smallint] NULL,
[Badge19] [smallint] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Badge] WITH CHECK ADD CONSTRAINT [Badge_FK00] FOREIGN KEY([Id_Operatore])
REFERENCES [dbo].[Operatori] ([ID_Operatore])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Badge] CHECK CONSTRAINT [Badge_FK00]
GO
You should add an index on the foreign key.
The index might be covering, so including all these badges is not a bad idea.
Create a clustered (preferred) or nonclustered index on [Id_Operatore].
"Clustered" keeps the data physical by each other.
This reduces the IO on delete.

SQL Server 2008 FactFinance primary key

I have a problem with this script
SET ANSI_NULLS ON
GO
IF NOT EXISTS (SELECT * FROM [sys].[tables]
WHERE [object_id] = OBJECT_ID(N'[dbo].[FactFinance]')
AND OBJECTPROPERTY([object_id], N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[FactFinance]
(
[FinanceKey] [int] IDENTITY PRIMARY KEY NOT NULL,
[TimeKey] [int] NULL,
[OrganizationKey] [int] NULL,
[DepartmentGroupKey] [int] NULL,
[ScenarioKey] [int] NULL,
[AccountKey] [int] NULL,
[Amount] [float] NULL
) ON [PRIMARY];
END
GO
SET ANSI_NULLS OFF
GO
When I run this, I get this result:
but if I remove this line [Finance Key] [int] IDENTITY PRIMARY KEY NOT NULL, from the script, it works

Get distinct rows in sql server when one to many relationship

I have 2 tables (BSH_FLD1) and (BSH_IMGVER).These tables are related by a third table called (BSH_FLDIMG1).One id field in (BSH_FLD1) can relate to many id images in (BSH_IMGVER).
The script for creating the tables is this :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BSH_FLD1](
[IDFIELD] [int] NOT NULL,
[EC_NOP] [int] NULL,
[EC_NOI] [int] NULL,
[EC_NOA] [int] NULL,
[INTESTIMI] [varchar](20) COLLATE Albanian_CI_AI NULL,
[KUTIA] [int] NULL,
[DREJTORIA] [varchar](30) COLLATE Albanian_CI_AI NULL,
[DOSJA] [int] NULL,
[VITI] [int] NULL,
[AFATI] [varchar](20) COLLATE Albanian_CI_AI NULL,
[FILLIMI] [datetime] NULL,
[FUNDI] [datetime] NULL,
[FAQE] [int] NULL,
[FILMI] [int] NULL,
[BLIP] [varchar](10) COLLATE Albanian_CI_AI NULL,
[DEPARTAMENTI] [varchar](150) COLLATE Albanian_CI_AI NULL,
[LLOJI_I_DOKUMENTIT] [varchar](50) COLLATE Albanian_CI_AI NULL,
[ADRESIMI] [varchar](30) COLLATE Albanian_CI_AI NULL,
[KLASIFIKIMI] [varchar](30) COLLATE Albanian_CI_AI NULL,
[KOMENTE] [varchar](255) COLLATE Albanian_CI_AI NULL,
[FRAKSION] [int] NULL,
[OBJEKTI] [varchar](50) COLLATE Albanian_CI_AI NULL,
CONSTRAINT [P080318150042500] PRIMARY KEY CLUSTERED
(
[IDFIELD] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BSH_FLDIMG1](
[IDFIELD] [int] NOT NULL,
[IDIMAGE] [int] NOT NULL,
CONSTRAINT [P080318150042718] PRIMARY KEY CLUSTERED
(
[IDFIELD] ASC,
[IDIMAGE] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [eCodis_Data]
GO
ALTER TABLE [dbo].[BSH_FLDIMG1] WITH CHECK ADD CONSTRAINT [F080318150042828] FOREIGN KEY([IDFIELD])
REFERENCES [dbo].[BSH_FLD1] ([IDFIELD])
GO
ALTER TABLE [dbo].[BSH_FLDIMG1] WITH CHECK ADD CONSTRAINT [F080318150042937] FOREIGN KEY([IDIMAGE])
REFERENCES [dbo].[BSH_IMG] ([IDIMAGE])
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BSH_IMGVER](
[IDIMAGE] [int] NOT NULL,
[VERSION] [int] NOT NULL,
[IDDATASET] [int] NULL,
[IDVOLUME] [int] NULL,
[IMAGE] [varchar](250) COLLATE Albanian_CI_AI NULL,
[CHECKEDOUT] [smallint] NULL,
[CHECKOUTBY] [varchar](250) COLLATE Albanian_CI_AI NULL,
[ADDDATE] [datetime] NULL,
[ADDBY] [varchar](250) COLLATE Albanian_CI_AI NULL,
[ORGFNAME] [varchar](250) COLLATE Albanian_CI_AI NULL,
[NROFPAGES] [int] NULL,
CONSTRAINT [P080318150040953] PRIMARY KEY CLUSTERED
(
[IDIMAGE] ASC,
[VERSION] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
USE [eCodis_Data]
GO
ALTER TABLE [dbo].[BSH_IMGVER] WITH CHECK ADD CONSTRAINT [F080318150041062] FOREIGN KEY([IDIMAGE])
REFERENCES [dbo].[BSH_IMG] ([IDIMAGE])
GO
ALTER TABLE [dbo].[BSH_IMGVER] WITH CHECK ADD CONSTRAINT [F080318150041171] FOREIGN KEY([IDDATASET])
REFERENCES [dbo].[BSH_DATASET] ([IDDATASET])
GO
ALTER TABLE [dbo].[BSH_IMGVER] WITH CHECK ADD CONSTRAINT [F080318150041281] FOREIGN KEY([IDVOLUME])
REFERENCES [dbo].[VOLUME] ([IDVOLUME])
I want to take distinct rows but since the relation is one to many the following query gives all the id fields that relate to an id image
Select DISTINCT
BSH_FLD1.IDFIELD as name,
'Dosje' as type,
'arkivuar' as 'ecm:currentLifeCycleState',
BSH_FLD1.IDFIELD as 'dc:title',
BSH_FLD1.IDFIELD,
BSH_FLD1.EC_NOP,
BSH_FLD1.EC_NOI,
BSH_FLD1.EC_NOA,
BSH_FLD1.INTESTIMI,
BSH_FLD1.KUTIA,
BSH_FLD1.DREJTORIA,
BSH_FLD1.DOSJA,
BSH_FLD1.VITI,
BSH_FLD1.AFATI,
CONVERT(VARCHAR(10), BSH_FLD1.FILLIMI,103) as FILLIMI,
CONVERT(VARCHAR(10),BSH_FLD1.FUNDI,103) as FUNDI,
BSH_FLD1.FAQE,
BSH_FLD1.FILMI,
BSH_FLD1.BLIP,
BSH_FLD1.DEPARTAMENTI,
BSH_FLD1.LLOJI_I_DOKUMENTIT,
BSH_FLD1.ADRESIMI,
BSH_FLD1.KLASIFIKIMI,
BSH_FLD1.KOMENTE,
BSH_FLD1.FRAKSION,
BSH_FLD1.OBJEKTI,
BSH_IMGVER.IDIMAGE,
BSH_IMGVER.VERSION,
BSH_IMGVER.IDDATASET,
BSH_IMGVER.IDVOLUME,
BSH_IMGVER.IMAGE as 'file:content',
BSH_IMGVER.CHECKEDOUT,
BSH_IMGVER.CHECKOUTBY,
CONVERT(VARCHAR(10),BSH_IMGVER.ADDDATE,103) as ADDDATE,
BSH_IMGVER.ADDBY,
BSH_IMGVER.ORGFNAME,
BSH_IMGVER.NROFPAGES
From BSH_FLDIMG1
JOIN BSH_FLD1 ON BSH_FLDIMG1.IDFIELD = BSH_FLD1.IDFIELD
JOIN BSH_IMGVER ON BSH_FLDIMG1.IDIMAGE = BSH_IMGVER.IDIMAGE
This brings me for example id field 1-idimage 1 and idfield 1-idimage 2
.I want only one row for one id field.
Now the result set is:
|name|type |.......|idImage|
|1 |Dosje|.......|1
|1 |Dosje|.......|2
|2 |Dosje|.......|3
|2 |Dosje|.......|4
|2 |Dosje|.......|5
I want to have the following :
|name|type |.......|idImage|
|1 |Dosje|.......|1
|2 |Dosje|.......|3
Can someone help me??

Error while querying the partitioned table in SQL Server

I have created a partition table and trying to query the partition but not able to do so in sql server 2016. Could somebody tell me where I am going wrong
CREATE PARTITION FUNCTION [financialStatementPartition](datetime)
AS RANGE RIGHT FOR VALUES (N'2013-01-01T00:00:00.000', N'2014-01-01T00:00:00.000',
N'2015-01-01T00:00:00.000', N'2016-01-01T00:00:00.000',
N'2017-01-01T00:00:00.000')
GO
Table schema
CREATE TABLE [dbo].[FinancialStatementIds]
(
[financialCollectionId] [int] NOT NULL,
[companyId] [int] NOT NULL,
[dataItemId] [int] NOT NULL,
[dataItemName] [varchar](200) NULL,
[dataItemvalue] [decimal](18, 0) NULL,
[unittypevalue] [int] NULL,
[fiscalyear] [int] NULL,
[fiscalquarter] [int] NULL,
[periodenddate] [datetime] NULL,
[filingdate] [datetime] NULL,
[restatementtypename] [varchar](200) NULL,
[latestforfinancialperiodflag] [bit] NULL,
[latestfilingforinstanceflag] [bit] NULL,
[currencyconversionflag] [int] NULL,
[currencyname] [varchar](200) NULL,
[periodtypename] [varchar](200) NULL
)
Query
SELECT *
FROM dbo.FinancialStatementIds
WHERE $PARTITION.financialStatementPartition(periodenddate) = '2013-01-01T00:00:00.000'
Error
Conversion failed when converting the varchar value '2013-01-01T00:00:00.000' to data type int.
Use following query instead:
SELECT *
FROM dbo.FinancialStatementIds
WHERE periodenddate = '20130101'
Anyway, the table is still not partitioned properly. You need to apply Partition Scheme to connect the table and Partition function.

Stored procedure query for selecting values

I have a Test table
CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL,
and Questions table as
CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL,
Questions table stores all the questions for each test with Tid as foreign key.
I want to write a stored procedure to fetch TestName, TestId and number of questions in each test in a single stored procedure. But I am unable to get this.
You can write the stored procedure as:
CREATE PROCEDURE [dbo].[procGetNumberofQuestionsForTest]
AS
BEGIN
SELECT T.[TestId], T.[TestName], COUNT(Q.[Qid]) AS NumberOfQuestions
FROM [dbo].[Test] T
JOIN [dbo].[Questions] Q ON Q.Tid = T.TestId
GROUP BY T.[TestId], T.[TestName]
END
If you want to get the result for specific Test, then pass the parameter as #TestId INT and add the WHERE clause as WHERE T.[TestId] = #TestId before the GROUP BY.
Try this (table create, insert, proc creation and execution included);
CREATE TABLE [dbo].[Test](
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](50) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL)
go
CREATE TABLE [dbo].[Questions](
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL
)
go
insert into [dbo].[Test]
values('test #1',1,0)
go
insert into [dbo].[Questions]
values(1,1,'what is life',0)
go
create proc dbo.MyInfo
as
select
t.TestName,
t.TestId,
[No Questions]=COUNT(q.Qid)
from
[dbo].[Test] t
inner join
[dbo].[Questions] q on t.TestId=q.Qid
group by
t.TestName,
t.TestId
go
exec dbo.MyInfo
go

Resources