SQLServer how to convert single row values in to multiple rows with each property as separat - sql-server-2017

I have a user defined type which is passed to my sql stored procedure:
CREATE TYPE [dbo].[LearningDelivery] AS TABLE(
[LearnAimRef] NVARCHAR(10) NOT NULL,
[AimType] INT NOT NULL,
[AimSeqNumber] INT NOT NULL,
);
i have a table with structure as below. I want to match join the type name from the above definition into the ElementName column of the FieldDefinitation table and insert separate insert statements. can anyone help me how to achieve this?
CREATE TABLE [dbo].[LearningAimData]
(
[Id] INT IDENTITY(1, 1) NOT NULL,
[LearnerId] INT NOT NULL,
[FieldId] INT NOT NULL,
[Data] VARCHAR(128) NOT NULL
)
I want to insert each type i.e LearnAimRef , AimType as individual row values in the LearningAimData.
I have a lookup table for [FieldId]
CREATE TABLE [dbo].[FieldDefinition]
(
[Id] INT IDENTITY(1, 1),
[FieldId] INT NOT NULL,
[Name] VARCHAR(50) NOT NULL,
[ElementName] VARCHAR(50) NOT NULL
)

Related

Make a column required if other column is of certain value

What I have:
CREATE TABLE [dbo].[User]
(
[id] INT NOT NULL PRIMARY KEY,
[name] VARCHAR(50) NOT NULL,
[postcode] INT NOT NULL,
[phone] INT NULL
)
What I want is that the phone number is required ONLY if the postcode is higher than 40000. If postcode is smaller than 40000, user can insert the phone number, although it is not required.
How do I do this?
You can use a check constraint:
CREATE TABLE [dbo].[User]
(
[id] INT NOT NULL PRIMARY KEY,
[name] VARCHAR(50) NOT NULL,
[postcode] INT NOT NULL,
[phone] INT NULL,
CONSTRAINT CHK_Postcode CHECK (postcode >= 4000 OR Phone IS NOT NULL)
);
This needs to be handled from the front end inserting values into the Database. Insert Query on one column based on another in the DB for the same table is not possible.

Error relate SQL Server tables

I have the following problem: when we run the code, it displays the following error:
There are primary keys or candidates in the reference Ticket table
that match the list of referencing columns in foreign key '
FK__Payment__PkTicke__1A14E395
Code:
create table SystemUser
(
PkUser int identity(1,1),
UserLogin nvarchar(20) not null unique,
UserPassword nvarchar(50) not null,
UserName nvarchar(50) not null,
UserCpf nvarchar(50) not null,
UserBirth datetime not null,
UserGender nvarchar(15) not null,
AddressCep int not null,
AddressStreet nvarchar(50) not null,
AddressNumber nvarchar(20) not null,
AddressComplement nvarchar(50) not null,
AddressCity nvarchar(50) not null,
AddressState nvarchar(50) not null,
primary key(PkUser)
)
create table Attractions
(
PkAttraction integer identity(1,1) ,
AttractionName nvarchar(50) not null unique,
AttractionDate datetime not null,
AttractionDescription nvarchar(150) not null
primary key(PkAttraction)
)
create table Ticket
(
PkTicket int identity(1,1),
PkUser int not null,
PkAttraction int not null,
TicketPrice decimal not null,
primary key(PkTicket, PkUser, PkAttraction),
foreign key(PkUser) references SystemUser(PkUser),
foreign key(PkAttraction) references Attractions(PkAttraction)
)
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
foreign key(PkTicket) references Ticket(PkTicket),
)
create table FormPayment
(
PkFromPayment int identity(1,1),
PkPayment int not null,
ShareValue decimal not null,
ExpirationDate datetime not null
primary key(PkFromPayment, PkPayment),
foreign key(PkPayment) references Payment(PkPayment),
)
Your Ticket table as a primary key made up from 3 columns:
create table Ticket
(
.....
primary key(PkTicket, PkUser, PkAttraction),
....
)
Any table that wants to reference that table Ticket must also provide all 3 columns for the foreign key.
You cannot reference only part of a primary key - if you want to reference it, you must have all columns that it contains - otherwise you cannot establish a FK relationship.
So you must add the PkUser and PkAttraction columns to your Payment table so that you can establish this FK relationship:
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
PkUser int not null, // add this
PkAttraction int not null, // add this
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
// change to this
foreign key(PkTicket, PkUser, PkAttraction) references Ticket(PkTicket, PkUser, PkAttraction)
.....
)
When you not specify a name for FK and PK, SQL server generates a name. in this case, looks like SQL server generates duplicate name.
If you specify name for FK and PK, it will work.

Can one table have two identity columns in SQL Server?

I am trying to make two columns auto increment but this column shows an error [user_id] as id + 0 PRIMARY KEY NOT NULL saying
Only UNIQUE or PRIMARY KEY constraints can be created on computed columns
What I am trying to do is, if id = 1, make user_id= 1 as well.
CREATE TABLE [dbo.TBL_TXN_USER]
(
[id] int NOT NULL IDENTITY(1,1),
[user_id] as id + 0 PRIMARY KEY NOT NULL ,
[username] varchar(150) NOT NULL,
[fullname] varchar(150) NOT NUll,
[pwd] varchar(50) NOT NUll,
[email] varchar(150) NOT NULL,
[mobile] varchar(150) NOT NULL,
[designation] varchar(150) NOT NULL,
[deleted] int NULL,
[created_date] datetime NULL,
[creator_user_id] int NULL,
[changed_date] datetime NULL,
[changer_user_id] int NULL,
[add_content] int NULL,
[edit_content] int NULL,
[delete_content] int NULL,
[manage_user] int NULL,
[view_log] int NULL,
)
What is wrong in [user_id]? How to solve it?
the error message is because you put the NOT NULL constraint on the computed column.
on sql server 2012 the complete error message is:
Only UNIQUE or PRIMARY KEY constraints can be created on computed
columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require
that computed columns be persisted.
here is a working script (i changed the table name):
CREATE TABLE dbo.[TBL_TXN_USER]
(
[id] int NOT NULL IDENTITY(1,1),
[user_id] as id + 0 persisted not null primary key,
[username] varchar(150) NOT NULL,
[fullname] varchar(150) NOT NUll,
[pwd] varchar(50) NOT NUll,
[email] varchar(150) NOT NULL,
[mobile] varchar(150) NOT NULL,
[designation] varchar(150) NOT NULL,
[deleted] int NULL,
[created_date] datetime NULL,
[creator_user_id] int NULL,
[changed_date] datetime NULL,
[changer_user_id] int NULL,
[add_content] int NULL,
[edit_content] int NULL,
[delete_content] int NULL,
[manage_user] int NULL,
[view_log] int NULL,
);
GO
i have a couple of comments about that question .
- a calculated field with a fixed formula with static values as primary key instead of the id itself is a waste of resources: one of the 2 fields should not be there
- a field with the name of a system function (user_id) is something i would avoid at all costs.
- the question looks like an attempt to put in place a solution (the calculated field as id) for an hidden issue.
Sorry for my misunderstanding, So you want to add auto increments two column in one table. Actually that is not accept at SQL-server so I am going to give you another option below
CREATE TRIGGER [dbo].[insert_triger] ON [dbo].[TBL_TXN_USER]
FOR INSERT
AS
update TBL_TXN_USER set [user_id] = id
where id = (
select MAX(id)
from TBL_TXN_USER
)
column aliases work with select statement not create table, also for [user_id] you didn't provide any data type.
Use the following to create your table :
CREATE TABLE [dbo.TBL_TXN_USER](
[id] int NOT NULL IDENTITY(1,1),
[user_id] int PRIMARY KEY NOT NULL ,
....rest of code
To update [user_id] consider using a trigger.

Retrieve data using select query with null Foreign key value

I have a 2 tables with name Vendor and VendorType . Structure are given
CREATE TABLE XCodesSCMERP.dbo.Vendor (
VendorID INT IDENTITY,
VendorTypeID INT NULL,
VendorName VARCHAR(200) NULL,
VendorCompany VARCHAR(200) NULL,
FirstName VARCHAR(100) NULL,
LastName VARCHAR(100) NULL,
Contact VARCHAR(100) NULL,
Phone VARCHAR(100) NULL,
AltContact VARCHAR(100) NULL,
Email VARCHAR(50) NULL,
AddressBilledFrom VARCHAR(50) NULL,
AddressShippedFrom VARCHAR(50) NULL,
VendorNotes VARCHAR(500) NULL,
OpeningBalance VARCHAR(100) NULL,
OpeningDate VARCHAR(100) NULL,
VendorAccountNo VARCHAR(100) NULL,
CONSTRAINT PK_Vendor PRIMARY KEY CLUSTERED (VendorID),
CONSTRAINT FK_Vendor_VendorTypeTable_VendorTypeID FOREIGN KEY (VendorTypeID) REFERENCES dbo.VendorTypeTable (VendorTypeID)
) ON [PRIMARY]
GO
CREATE TABLE XCodesSCMERP.dbo.VendorTypeTable (
VendorTypeID INT IDENTITY,
VendorType VARCHAR(100) NULL,
VendorDesc VARCHAR(MAX) NULL,
CONSTRAINT PK_VendorTypeTable PRIMARY KEY CLUSTERED (VendorTypeID)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
It is clear from structures of table that VendorTypeID is foreign key in Vendor table. Now when i want to retrieve data from Vendor table including field VendorType from VendorTypeTable than i have to use Inner Join that works fine.
But here is problem . it does' not show that records which don't have any vendorType i.e VendorTypeID is not selected . It is said to be null.
Now here is my question , how i can retrieve those records also that don't have any Vendor Type.
Would be pleasure for me , helping me in my Problem.
Note:
SELECT VendorID,VendorName,FirstName,LastName,VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo ,VendorNotes FROM Vendor WHERE VendorTypeID='';
This query does not return any record.
If I understand correctly, you just want IS NULL:
SELECT v.*
FROM Vendor v
WHERE VendorTypeID IS NULL;
Modify your query to something like this
SELECT
VendorID,VendorName,FirstName,LastName,VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo
,VendorNotes FROM Vendor WHERE VendorTypeID IS NULL;
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is a blank field

SQL Server Copy records from one column to another

How to pass data from one column to another column in the same table?i.e:
create table tb_usuarios_voar
(
int_id_usu int identity(1,1),
int_re_usu int not null,
txt_colaborador varchar(200) null,
txt_cargo varchar(200) null,
txt_chefearea_usu varchar(150) null,
txt_estrutura varchar(200) null,
txt_marca varchar(200) null,
txt_unidade varchar(150) null
)
That is the original table.Then ive added a new column:
alter table tb_usuarios_voar add txt_password varchar(140) null
What i want is to copy all records from int_re_usu column to the new column txt_password.
Any ideias?
update tb_usuarios_voar set txt_password = convert(varchar, int_re_usu)