I want to convert the following SQL server query into a Teradata BTEQ script. Could anyone help in this process..
The table creation logic is as follows and this needs to be converted to Teradata
CREATE TABLE [Eqp].[t_WSTCPEStairstep]
(
[SysID] [smallint] NULL,
[PrinID] [smallint] NULL,
[Account] [bigint] NOT NULL,
[Order_No] [bigint] NOT NULL,
[Order_Typ] [varchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Eqp_Serial] [varchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Eqp_Typ] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Eqp_Model] [varchar] (9) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Disco_Dte] [date] NULL,
[Return_Dte] [date] NULL,
[Restart_Dte] [date] NULL,
[Lost_Dte] [date] NULL,
[TestFlag] [smallint] NULL
) ON [PRIMARY]
WITH
(
DATA_COMPRESSION = PAGE
)
GO
CREATE NONCLUSTERED INDEX [ix_WSTCPEStairstepDiscoDteIndex] ON [Eqp].[t_WSTCPEStairstep] ([Disco_Dte]) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX [ix_WSTCPEStairstepSPAIndex] ON [Eqp].[t_WSTCPEStairstep] ([SysID], [Account]) WITH (DATA_COMPRESSION = PAGE) ON [PRIMARY]
GO
I'm not sure about some of the SQL Server specific bits (compression, clustered, primary), but this will give you a start:
CREATE TABLE Eqp.t_WSTCPEStairstep (
SysID SMALLINT,
PrinID SMALLINT,
Account BIGINT NOT NULL,
Order_No BIGINT NOT NULL,
Order_Typ VARCHAR(1),
Eqp_Serial VARCHAR(25),
Eqp_Typ VARCHAR(2),
Eqp_Model VARCHAR(9) ,
Disco_Dte DATE,
Return_Dte DATE,
Restart_Dte DATE,
Lost_Dte DATE,
TestFlag SNALLINT
)
PRIMARY INDEX(col1, col2, ...);
-- Indexes
CREATE INDEX ix_WSTCPEStairstepDiscoDteIndex (Disco_Dte) ON Eqp.t_WSTCPEStairstep;
CREATE INDEX ix_WSTCPEStairstepSPAIndex (SysID, Account) ON Eqp.t_WSTCPEStairstep;
Which column(s) do you use to access data in this table? If they provide even distribution (i.e. mostly distinct values), then specify these as your PRIMARY INDEX fields. And if these fields are unique, better yet - UNIQUE PRIMARY INDEX. Maybe it's one of the indexes you specified -- disco_dte or (SysID, Account).
Some more notes:
columns should be NULLABLE by default
if TestFlag is just 1/0, you can use the BYTEINT data type
you may want to convert the VARCHAR(1) and VARCHAR(2) to CHAR
for compression, you can add that at multiple levels, but most common I think is at the column level
Related
I'm reverse engineering a script that creates a payroll database from my textbook. I'm rebuilding it into a library management system instead. To start I've drawn out a diagram of the tables/columns and their relationships here. Now following the script from the textbook I use the authors technique to create all the tables except for the BooksIssued table and InvoiceItems table. This is my code
USE master
GO
/******Check to see if database exists******/
IF DB_ID('SET2133810') IS NOT NULL
DROP DATABASE SET2133810
GO
/******Object: Database SET2133810******/
CREATE DATABASE SET2133810
GO
USE SET2133810
GO
/******Object: table*****/
CREATE TABLE VendorsList(
VendorID int IDENTITY(1,1) NOT NULL,
VendorName varchar(50) NOT NULL,
VendorPhone varchar(50) NULL,
VendorContactLName varchar(50) NULL,
VendorContactFName varchar(50) NULL,
VendorAddress varchar(50) NULL,
VendorCity varchar(50) NOT NULL,
VendorState char(2) NOT NULL,
VendorZipCode varchar(20) NOT NULL,
CONSTRAINT PK_VendorsList PRIMARY KEY CLUSTERED (
VendorID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE InvoicesList(
InvoiceID int IDENTITY(1,1) NOT NULL,
VendorID int NOT NULL,
InvoiceNumber varchar(50) NOT NULL,
InvoiceDate smalldatetime NOT NULL,
InvoiceTotal money NOT NULL,
PaymentTotal money NOT NULL,
PaymentDate smalldatetime NULL,
CONSTRAINT PK_InvoicesList PRIMARY KEY CLUSTERED(
InvoiceID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE BookList(
BookID int IDENTITY(1,1) NOT NULL,
BookISBN varchar(50) NOT NULL,
BookTitle varchar(50) NOT NULL,
BookAuthor varchar(50) NOT NULL,
BookPublisher varchar(50) NOT NULL,
BookGenre varchar(50) NULL
CONSTRAINT PK_BookList PRIMARY KEY CLUSTERED(
BookID ASC
)
)
GO
/******Object: Table*****/
CREATE TABLE MembersList(
MemberID int IDENTITY(1,1) NOT NULL,
MemberLName varchar(50) NOT NULL,
MemberFName varchar(50) NOT NULL,
MemberAddress varchar(50) NULL,
MemberCity varchar(50) NOT NULL,
MemberState char(2) NOT NULL,
MemberZipCode varchar(20) NOT NULL,
MemberPhone varchar(50) NOT NULL,
MemberEmail varchar(50) NOT NULL,
CONSTRAINT PK_MembersList PRIMARY KEY CLUSTERED(
MemberID ASC
)
)
GO
I'm confused on how I would create these tables in the same way? Since they both depend on the other tables and the information thats already in them. I've looked around and found Join statements, but none of them were used in a way that would help me with this problem.
Following should be the order to create tables.
BookList
MemeberList
Book Issued
VendorList
InvoiceList
InvoiceItems
Invoice list shoul be created in last as it have references to vendor and invoice items and BookIssues should be created after MemberList and Book List
As we have regulation changes coming in force in the UK soon a database that I am working on that needs to be updated to have any personal identifiable information encrypted.
A number of my tables have been altered successfully, however on some tables where there are triggers I am getting the following error.
Error SQL72014: .Net SqlClient Data Provider: Msg 206, Level 16, State 2, Procedure tr_Employee_Update, Line 27 Operand type clash: varchar is incompatible with varchar(max) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'xxxx') collation_name = 'Latin1_General_BIN2'
I have looked at this question here, however this doesnt solve my issue Operand type clash: varchar is incompatible with varchar(50) trying to insert in encrypted database
Same with this question too where is doesnt address my issue exactly. SQL Server Always Encrypted Operand type clash: varchar is incompatible with varchar(60) when running EXEC sproc.
I have this issue on a number of tables so would be grateful for any and all help.
Please see the SQL Fiddle here
http://sqlfiddle.com/#!18/4ac5c/3
I have had to split the table and trigger creation because the SQL length is greater than 8000 characters but this is the fullest example I can give.
I am encrypting the columns using Encryption type: Deterministic and Encryption key name: CEK_Auto1.
Not all columns in this table need encrypting and I am altering some of the other fields that have default values too where encryption does need to take place.
Any and all help on the reported issue would be gratefully received.
CREATE TABLE [dbo].[Employee] (
[EmployeeID] INT IDENTITY (1, 1) NOT NULL,
[EmployeeTypeID] INT NOT NULL,
[Title] VARCHAR (50) NOT NULL,
[Forename] VARCHAR (30) NOT NULL,
[Surname] VARCHAR (30) NOT NULL,
[AddressLine1] VARCHAR (60) NOT NULL,
[AddressLine2] VARCHAR (60) NOT NULL,
[AddressLine3] VARCHAR (60) NOT NULL,
[AddressLine4] VARCHAR (60) NOT NULL,
[Town] VARCHAR (50) NOT NULL,
[County] VARCHAR (50) NOT NULL,
[PostCode] VARCHAR (20) NOT NULL,
[Phone] VARCHAR (20) CONSTRAINT [DF_Employee_Phone] DEFAULT ('') NOT NULL,
[Mobile] VARCHAR (20) NOT NULL,
[Fax] VARCHAR (20) NOT NULL,
[Email] VARCHAR (50) NOT NULL,
[Extension] VARCHAR (10) CONSTRAINT [DF_Employee_Extension_1] DEFAULT ('') NOT NULL,
[SpeedDial] VARCHAR (10) CONSTRAINT [DF_Employee_SpeedDial_1] DEFAULT ('') NOT NULL,
[Notes] VARCHAR (MAX) NOT NULL,
[EmployeeTeamID] INT NULL,
[Created] DATETIME CONSTRAINT [DF_Employee_Created] DEFAULT (getdate()) NOT NULL,
[OperatorIDCreated] INT NOT NULL,
[Updated] DATETIME CONSTRAINT [DF_Employee_Updated] DEFAULT (getdate()) NOT NULL,
[OperatorIDUpdated] INT NOT NULL,
[Deleted] BIT CONSTRAINT [DF_Employee_Deleted] DEFAULT ((0)) NOT NULL,
[EmployeeIDManager] INT NULL,
[JobTitle] VARCHAR (100) CONSTRAINT [DF_Employee_JobTitle] DEFAULT ('') NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmployeeID] ASC),
CONSTRAINT [FK_Employee_Employee] FOREIGN KEY ([EmployeeIDManager]) REFERENCES [dbo].[Employee] ([EmployeeID]),
CONSTRAINT [FK_Employee_EmployeeTeam] FOREIGN KEY ([EmployeeTeamID]) REFERENCES [dbo].[EmployeeTeam] ([EmployeeTeamID]),
CONSTRAINT [FK_Employee_EmployeeType] FOREIGN KEY ([EmployeeTypeID]) REFERENCES [dbo].[EmployeeType] ([EmployeeTypeID])
);
GO
CREATE NONCLUSTERED INDEX [IX_Employee_Surname]
ON [dbo].[Employee]([Surname] ASC);
GO
CREATE TABLE [dbo].[AuditItem](
[AuditItemID] [INT] IDENTITY(1,1) NOT NULL,
[ID] [INT] NOT NULL,
[AuditEntityID] [INT] NOT NULL,
[AuditTypeID] [INT] NOT NULL,
[Note] [VARCHAR](MAX) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[Created] [DATETIME] NOT NULL,
[OperatorIDCreated] [INT] NOT NULL,
[ProfessionalIDCreated] [INT] NULL,
CONSTRAINT [PK_AuditItem] PRIMARY KEY CLUSTERED
(
[AuditItemID] 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 Trigger [dbo].[tr_Employee_Update] ON [dbo].[Employee]
FOR UPDATE
AS
--Audit Entity ID for Employees
Declare #AuditEntityID int
set #AuditEntityID = 2
Insert AuditItem
(ID,AuditEntityID,AuditTypeID, Note, Created, OperatorIDCreated)
Select
inserted.EmployeeID,
#AuditEntityID,
--Update type
2,
'Name changed from ' + ltrim(rtrim(ltrim(rtrim(Deleted.Title)) + ' ' + ltrim(rtrim(Deleted.Forename)) + ' ' + ltrim(rtrim(Deleted.Surname)))) + ' to ' + + ltrim(rtrim(ltrim(rtrim(Inserted.Title)) + ' ' + ltrim(rtrim(Inserted.Forename)) + ' ' + ltrim(rtrim(Inserted.Surname)))),
GetDate(),
inserted.OperatorIDUpdated
From inserted
Inner Join deleted on inserted.EmployeeID = deleted.EmployeeID
Where deleted.Title <> inserted.Title or deleted.Forename <> inserted.Forename or deleted.Surname <> inserted.Surname
After much research into this today it is unfortunate at the moment that triggers are not supported to update Encrypted Columns regardless of the data type. So anyone who stumbled across this question and is having the same issue you will need to complete your updates through stored procedures but they will need to be called via application code.
Although the two linked questions in my question above do not directly address my question or help me, you may need to follow the answers in the questions to help you should you need to pass parameterised values to a stored procedure and have issues.
I have written the following stored procedure to return data based on a lat/long and category id being passed.
I need to return a list of traders whose coverage area falls within the passed lat long (and that they cover the category being passed). So I am looking to draw a circle around the traders lat/long position, x number of meters using the radius they will operate from (this is stored in the Traders.OperatingRadius column). If the passed lat long coord is within this, then they should be included in the return list.
CREATE PROCEDURE FindTradersWithinRadiusLatLong
#LAT decimal(9,6),
#LONG decimal(9,6),
#CATEGORY int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #GEO1 GEOGRAPHY;
SET #GEO1 = geography::Point(#LAT, #LONG, 4326)
SELECT
x.Id, x.Name,
x.Latitude, x.Longitude,
x.Distance, x.IsArchived
FROM
(SELECT
Traders.Id, Traders.Name,
Latitude, Longitude,
CategoryId = TraderCategories.Id,
OperatingRadius,
Traders.IsArchived,
Distance = (#geo1.STDistance(geography::Point(ISNULL(Latitude, 0), ISNULL(Longitude, 0), 4326)))
FROM
((Addresses
INNER JOIN
Traders ON Addresses.TraderId = Traders.Id)
INNER JOIN
TraderCategories ON Traders.Id = TraderCategories.TraderId)) AS x
WHERE
x.Distance <= x.OperatingRadius
AND x.CategoryId = #CATEGORY
AND (x.IsArchived = 0 OR x.IsArchived = NULL);
END
GO
TraderCategories is a linking table as follows;
Table TraderCategories
int FK TraderId
int FK CategoryId
Now I have added an address with;
latitiude - 43.590000, Longitude - -111.120000
There is also a TraderCategory Relationship for category with Id 1
I have then tried calling the stored procedure with the above and no matches are being returned.
The table definitions are as follows:
CREATE TABLE [Bemfeito].[Addresses]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Address1] [nvarchar](max) NULL,
[Address2] [nvarchar](max) NULL,
[Address3] [nvarchar](max) NULL,
[TraderId] [int] NULL,
[Latitude] [decimal](9, 6) NOT NULL,
[Longitude] [decimal](9, 6) NOT NULL,
[OperatingRadius] [real] NOT NULL DEFAULT (CONVERT([real],(0)))
CONSTRAINT [PK_Addresses]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
ALTER TABLE [Bemfeito].[Addresses] WITH CHECK
ADD CONSTRAINT [FK_Addresses_Traders_TraderId]
FOREIGN KEY([TraderId]) REFERENCES [Bemfeito].[Traders] ([Id])
GO
ALTER TABLE [Bemfeito].[Addresses] CHECK CONSTRAINT [FK_Addresses_Traders_TraderId]
GO
CREATE TABLE [Bemfeito].[Traders]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](max) NULL
[Name] [nvarchar](max) NULL
CONSTRAINT [PK_Traders]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
CREATE TABLE [Bemfeito].[TraderCategories]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NULL,
[TraderId] [int] NULL,
CONSTRAINT [PK_TraderCategories]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
ALTER TABLE [Bemfeito].[TraderCategories] WITH CHECK
ADD CONSTRAINT [FK_TraderCategories_Categories_CategoryId]
FOREIGN KEY([CategoryId]) REFERENCES [Bemfeito].[Categories] ([Id])
GO
ALTER TABLE [Bemfeito].[TraderCategories] CHECK CONSTRAINT [FK_TraderCategories_Categories_CategoryId]
GO
ALTER TABLE [Bemfeito].[TraderCategories] WITH CHECK
ADD CONSTRAINT [FK_TraderCategories_Traders_TraderId]
FOREIGN KEY([TraderId]) REFERENCES [Bemfeito].[Traders] ([Id])
GO
ALTER TABLE [Bemfeito].[TraderCategories] CHECK CONSTRAINT [FK_TraderCategories_Traders_TraderId]
GO
and finally for completion the category
CREATE TABLE [Bemfeito].[Categories]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Value] [int] NOT NULL,
CONSTRAINT [PK_Categories]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
Can anyone tell me where I am going wrong here please?
If you look at this microsoft reference here you should notice that the argument passed to STDistance is a geometry datatype while you are passing a Point datatype.
the line currently written like this
,Distance = (#geo1.STDistance(geography::Point(ISNULL(Latitude, 0), ISNULL(Longitude, 0), 4326))
should be written as follows.
,Distance = (#geo1.STDistance(geography::STGeomFromText('Point('+ISNULL(Longitude, 0)+' '+ISNULL(Latitude, 0)')',4326))
I have two databases: identity2 and myDb.
Can someone help me by telling me how I can move the rows in a table with an identity column (AspNetUsers) from one database to another.
CREATE TABLE [dbo].[AspNetUsers] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (MAX) NULL,
[LastName] NVARCHAR (MAX) NULL,
[Email] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[LockoutEndDateUtc] DATETIME NULL,
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[UserName] NVARCHAR (256) NOT NULL,
[SubjectId] INT DEFAULT ((0)) NOT NULL,
[SubjectIds] VARCHAR (50) NULL,
[OrganizationId] INT DEFAULT ((0)) NOT NULL,
[OrganizationIds] VARCHAR (50) NULL,
[RoleId] INT DEFAULT ((0)) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([UserName] ASC);
What I want to do is to preserve the Id numbers but I don't know how to do this.
Create your table like you posted in the question and then do an insert with identity insert
SET IDENTITY_INSERT AspNetUsers ON
INSERT INTO AspNetUsers (
[Id],
[FirstName],
[LastName],
[Email],
[EmailConfirmed],
[PasswordHash],
[SecurityStamp],
[PhoneNumber],
[PhoneNumberConfirmed],
[TwoFactorEnabled],
[LockoutEndDateUtc],
[LockoutEnabled],
[AccessFailedCount],
[UserName],
[SubjectId],
[SubjectIds],
[OrganizationId],
[OrganizationIds],
[RoleId]
)
SELECT * FROM myDB.dbo.AspNetUsers
SET IDENTITY_INSERT AspNetUsers OFF
select *
into [targetdatabase].[dbo].[targettable]
from [sourcedatabase].[dbo].[sourcetable]
I'm fairly new to SQL Server any input and advice would help greatly.
I have 3 tables which are in one-to-many relationships.
Table Person holds customer info
CREATE TABLE [dbo].[Person](
[PID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](255) NULL,
[LastName] [varchar](255) NULL,
[CAddress] [varchar](255) NULL,
[Ccity] [varchar](255) NULL,
[Cstate] [varchar](2) NULL,
[Czipcode] [varchar](20) NULL,
[Ccountry] [varchar](255) NULL,
[Cphone] [varchar](25) NULL,
[Cemail] [varchar](255) NULL,
[CipAddress] [varchar](255) NULL)
Table Transaction holds their transaction
CREATE TABLE [dbo].[Transaction](
[TID] [int] IDENTITY(1,1) NOT NULL,
[PID] [int] NOT NULL,
[DateOfTransaction] [date] NULL)
with a third table, TransactionDetail, which holds transaction details
CREATE TABLE [dbo].[TransactionDetail](
[TDID] [int] IDENTITY(1,1) NOT NULL,
[TID] [int] NULL,
[ProductID] [int] NULL,
[ProductName] [varchar](255) NULL,
[ProductQTY] [int] NULL,
[ProductPrice] [decimal](18, 2) NULL)
I would like to create a stored procedure to insert once into the Person table then insert multiple details into the third table.
this is what i got i'm not sure if this is correct?
CREATE TYPE dbo.TransactionTableType AS TABLE
( TID int, ProductID int, ProductName varchar(255), ProductQTY int, ProductPrice decimal(18,2) )
go
CREATE PROCEDURE insertTransacion
#NewProduct dbo.TransactionTableType READONLY,
#FirstName varchar(255),
#LastName varchar(255),
#CAddress varchar(255),
#Ccity varchar(255),
#Cstate varchar(2),
#Czipcode varchar(20),
#Ccountry varchar(255),
#CPhone varchar(25),
#Cemail varchar(255),
#CipAddress varchar(255),
#DateOfTrans date
as
begin
SET NOCOUNT ON;
DECLARE #Pid int
insert into Person(FirstName,LastName,CAddress,Ccity,Cstate,Czipcode,Ccountry,Cphone,Cemail,CipAddress) values (#FirstName,#LastName,#CAddress,#Ccity,#Cstate,#Czipcode,#Ccountry,#CPhone,#Cemail,#CipAddress)
SET #Pid = SCOPE_IDENTITY()
insert into PTransactions(PID, DateOfTransaction) values (#Pid, #DateOfTrans)
DECLARE #Tid int
SET #Tid = SCOPE_IDENTITY()
insert into TransactionDetail(TID, ProductID, ProductName, ProductQTY, ProductPrice) Select #Tid, ntd.ProductID, ntd.ProductName, ntd.ProductQTY, ntd.ProductPrice from #NewProduct as ntd
end
Not sure how to do this in a stored procedure I know how to do it programmatically in asp.net using ado, however I'm trying to avoid that. Sorry for the grammar.
Short answer is you can't, although there are a couple of options open to you.
You can either create a SP to enter the person data, and a separate one to insert the data - one line at a time. Return the person id value with the first call and use that in the subsequent SP calls to insert the data. If you go down this path, make sure you wrap the calling code up in transaction objects so you can roll back the whole lot if you have a problem. You don't state what language you're using for the rest of your code?
Second option is to look at the SQL Bulk Insert command - this is best if you have a lot of data to add into the third table. But involves writing that data out to a file first - slight pain but it's then very fast. Very good if you have thousands or more rows to add.
Couple of other options out there as well depending on your development language.
Cheers
Simon