Can CAST and CONVERT be used in a table creation - sql

I have never tried this sort of SQL query before, so excuse me for asking this question. Is it possible to use CAST and CONVERT in a table creation?
create table Owner
(
Id int identity(0,1)
, Name nvarchar(200)
, CountryId int
, PolicyNumber AS (CONVERT(CountryId AS char(3)) + CONVERT(Id AS char(10)) varchar(40)
)
go

Yes, it is called computed columns but you use it wrong:
create table Owner(
Id int identity(0,1)
,Name nvarchar(200)
,CountryId int
,PolicyNumber AS (CAST(CountryId AS VARCHAR(10)) + CAST(Id AS VARCHAR(10)))
)
go
LiveDemo
No need for final datatype so remove varchar(40)
CAST(col AS datatype) or CONVERT(datatype, col, style). Don't mix them.
If you use SQL Server 2012+ use simple CONCAT:
create table Owner(
Id int identity(0,1)
,Name nvarchar(200)
,CountryId int
,PolicyNumber AS (CONCAT(CountryId, Id)));
go
You should also:
add NOT NULL and PRIMARY KEY to Id
add REFERENCES to CountryId and make it NOT NULL also
add separator to computed column like - between both number(see demo)

Related

How to add Nonunique index on table variable [duplicate]

This question already has answers here:
Creating an index on a table variable
(3 answers)
Closed 1 year ago.
I want to create a table in my function but I have trouble in adding nonunique index on OBJECT_ID.
DECLARE #VIEW_MY_DATA TABLE
(
[AREA_ID] INT,
[OBJECT_ID] INT,
[PARENT_ID] INT,
[OBJECT_TYPE] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
[RELATION] varchar(50)
)
I could not use CREATE TABLE in function. How to make it in SQL Server 2012?
Although you cannot add an index to an already declared table variable, you can specify indexes and constraints using inline syntax of the table declaration in SQL Server 2014 and later:
DECLARE #VIEW_MY_DATA TABLE
(
[AREA_ID] INT,
[OBJECT_ID] INT INDEX idx NONCLUSTERED,
[PARENT_ID] INT,
[OBJECT_TYPE] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
[RELATION] varchar(50)
)

creating custom_id using the concatenation of three columns

I have a table named Products having following columns:
create table Products
(ProductId int primary key identity(1,1),
GroupId int foreign key references ProductGroup(GroupId),
SubGroupId int foreign key references ProductSubGroup(SubGroupId),
Productcode as (GroupId + SubGroupId + ProductId),
ProductName nvarchar(50) not null unique,
ProductShortForm nvarchar(5) not null unique,
PiecesInCarton int not null,
WeightPerPiece decimal(4,2) not null,
PurchasePricePerCarton decimal(18,2) not null,
SalePricePerCarton_CatC decimal(18,2) not null,
SalePricePerCarton_CatB decimal(18,2) not null,
SalePricePerCarton_CatA decimal(18,2)
)
if GroupId = 34, SubGroupId = 22 and auto generated ProductId = 12
then ProductCode should be like 34-22-12
how do i do this?
Assuming you are using SQL Server, you would simply do:
Productcode as (concat(GroupId, '-', SubGroupId, '-', ProductId)),
The issue with your code is that + is interpreted as addition, rather than string concatenation.
In more recent versions, you can use concat_ws():
Productcode as (concat_ws('-', GroupId, SubGroupId, ProductId)),
CONCAT_WS allows you to specify a separator once to inject in between the instances that are being concatenated.
Also note that the inputs are implicitly converted to char types when you use CONCAT or CONCAT_WS so this syntax is simpler than other inline value concatenation methods.
I believe you are looking for a view from your table.
create view Products_View
as
select ProductId ,
GroupId,
SubGroupId,
Productcode as (GroupId + SubGroupId + ProductId) as ProductCode,
ProductName,
ProductShortForm,
PiecesInCarton,
WeightPerPiece,
PurchasePricePerCarton,
SalePricePerCarton_CatC,
SalePricePerCarton_CatB,
SalePricePerCarton_CatA
from products

Create SQL Function view with User ID and Date range

As I title says, I need to create a Function View of two tables.
Below are the SQL Tables
CREATE TABLE User_Specialist(
ID_User_Specialist INT NOT NULL,
Name_User_Specialist VARCHAR(50) NOT NULL,
CONSTRAINT PK_ID_User_Specialist PRIMARY KEY(ID_User_Specialist),
GO
CREATE TABLE Incident(
ID_Incident INT IDENTITY(1,1) NOT NULL,
Incident_Creation_Date DATETIME NULL,
Assigned_Specialist INT NULL,
CONSTRAINT FK_Assigned_Specialist FOREIGN KEY (Especialista_Asignado) REFERENCES Usuario_Especialista(ID_Usuario_Especialista),
GO
Based on the previous information, I need the function to display Assign Specialist and the dates that the Incident was created.
Right know this is what I got:
CREATE FUNCTION View_Date (#ID_User_Incident INT)
RETURNS INT
AS
BEGIN
DECLARE #Total_Incidents INT
SELECT #Total_Incidents = COUNT(ID_Incident)
FROM Incidents i, User_Specialist u
WHERE i.ID_Incident = u.ID_User_Specialist AND u.ID_User_Specialist =#ID_User_Incident
RETURN (#Total_Incidents)
END
GO
DECLARE #Specialist_ID int;
EXEC #Specialist_ID = [dbo].View_Date
#ID_Incidentes_Usuarios = 5;
SELECT #Specialist_ID AS 'Assigned Specialist Incidents'
GO
The only thing missing is the dates range.
I believe you changed your table and field names to English from Spanish. You have missed some of them and there were some missing parenthesis. As much as I understand I changed them to understand better.
CREATE TABLE User_Specialist
(
ID_User_Specialist INT NOT NULL,
Name_User_Specialist VARCHAR(50) NOT NULL
CONSTRAINT PK_ID_User_Specialist PRIMARY KEY(ID_User_Specialist)
)
GO
CREATE TABLE Incident
(
ID_Incident INT IDENTITY(1,1) NOT NULL,
Incident_Creation_Date DATETIME NULL,
Assigned_Specialist INT NULL
CONSTRAINT FK_Assigned_Specialist FOREIGN KEY (Assigned_Specialist) REFERENCES User_Specialist(ID_User_Specialist)
)
GO
If you want to see multiple columns or rows as result you need to use Table-valued Function. I have created sample query from your table and prepared function. you can change it with what you want.
CREATE FUNCTION dbo.FN_ViewDate
(
#ID_User_Incident INT
)
RETURNS #Result TABLE
(
TotalIncidents INT
,FirstIncidentDate DATETIME
,LastIncidentDate DATETIME
)
AS
BEGIN
INSERT INTO #Result
SELECT COUNT(ID_Incident)
,MIN(Incident_Creation_Date)
,MAX(Incident_Creation_Date)
FROM Incident I
LEFT JOIN User_Specialist U ON I.Assigned_Specialist = U.ID_User_Specialist
WHERE I.Assigned_Specialist = #ID_User_Incident
RETURN
END
GO
I think this query can help you.
declare #count int = 0 , #dates varchar(200) =''
SELECT #count+=1 , #dates +=' '+ i.Incident_Creation_Date
FROM Incidents i, User_Specialist u
WHERE i.ID_Incident = u.ID_User_Specialist AND u.ID_User_Specialist =#ID_User_Incident
select #count as [count] ,#dates [incidentDates]

Insert data into teable variable

I am trying to insert data through my stored procedure and finding difficulty in doing it.
I tried doing below code but it doesn't work.
DECLARE #AddressRecordsToPurge TABLE
(
RowID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
GUIDValue Nvarchar(max) NOT NULL,
GuidColumn Nvarchar(max) NOT NULL,
GuidTable Nvarchar(max) NOT NULL
)
Insert Into #AddressRecordsToPurge values ( Select AccountGUID FROM APPLICATIONCONTRACT WHERE ApplicationNumber =#ApplicationNumber AND AccountGUID IS NOT NULL, 'AccountGUID', 'PREVIOUSLENDERSREF');
my first value is query and last 2 values are strings. Please help me
I would write this as:
Insert Into #AddressRecordsToPurge (GUIDValue, GuidColumn, GuidTable)
Select AccountGUID, 'AccountGUID', 'PREVIOUSLENDERSREF'
from APPLICATIONCONTRACT
where ApplicationNumber = #ApplicationNumber and
AccountGUID IS NOT NULL;
Notes:
This explicitly lists the columns being inserted.
The identity column is not in the list, so it will get the default value.
There is no need for values, just insert . . . select.
As for your code, you need to remember that a subquery always needs to be surrounded by its own set of parentheses.
Alias string names as column names. When you declare a table variable you do not need to mention column names for insert unless you are inserting into few columns. Identity column will automatically populate.
DECLARE #AddressRecordsToPurge TABLE
(
RowID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
GUIDValue Nvarchar(max) NOT NULL,
GuidColumn Nvarchar(max) NOT NULL,
GuidTable Nvarchar(max) NOT NULL
)
Insert Into #AddressRecordsToPurge
SELECT
AccountGUID AS GUIDValue
,'AccountGUID' AS GuidColumn
,'PREVIOUSLENDERSREF' AS GuidTable
FROM APPLICATIONCONTRACT
WHERE ApplicationNumber =#ApplicationNumber AND AccountGUID IS NOT NULL
Try To This Way:
DECLARE #AddressRecordsToPurge TABLE
(
RowID INT NOT NULL
PRIMARY KEY
IDENTITY(1, 1) ,
GUIDValue NVARCHAR(MAX) NOT NULL ,
GuidColumn NVARCHAR(MAX) NOT NULL ,
GuidTable NVARCHAR(MAX) NOT NULL
)
INSERT INTO #AddressRecordsToPurge
( GUIDValue ,
GuidColumn ,
GuidTable
)
SELECT AccountGUID ,
'AccountGUID' ,
'PREVIOUSLENDERSREF'
FROM APPLICATIONCONTRACT AS artp
WHERE ApplicationNumber = #ApplicationNumber
AND AccountGUID IS NOT NULL

Auto increment number

Can you any one tell me how to generate auto number in SQL? I have tried but it shows the following error
"Incorrect sytnax near AUTO_INCREMENT".
What am I doing wrong?
create table auto1
(
Sno int NOT NULL AUTO_INCREMENT,
fname varchar(50)
)
I assume you are using SQL-Server where the syntax is different compared to other DB engines
create table auto1
(
Sno int NOT NULL IDENTITY(1,1),
fname varchar(50)
)
See here for details on table creation.
please try below one
CREATE TABLE test (
sno INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
fname VARCHAR( 20 ) NOT NULL
)