How to add Nonunique index on table variable [duplicate] - sql

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)
)

Related

Using int identity(1,1) as a way to join temporary tables

I'm rewriting a stored procedure that uses int identity(1,1) in >10 temp tables as a way to join these temp tables in the select statement. Below a shorter version of how how the code structure but in the stored procedure I'm editing there this structure is used to return data from each temp table.
CREATE TABLE #temp_MemberInfo
( RecID int identity(1,1),
MemberMBI varchar(13),
MemberName varchar(50),
MemberAddress varchar(150), -- DMP
MemberAddress2 varchar(100), -- DMP
MemberCity varchar(50),
MemberState varchar(3),
MemberZip varchar(11),
MemberMedicalRecordNo varchar(20),
MemberIsMale varchar(10),
MemberIsFemale varchar(10)
)
CREATE TABLE #temp_ProviderInfo
(
RecID int identity(1,1),
ProviderNPI varchar(13),
ProviderName varchar(60), -- DMP
ProviderAddress varchar(150), -- DMP
ProviderAddress2 varchar(100), -- DMP
ProviderCity varchar(40),
ProviderState varchar(3),
ProviderZip varchar(11),
ProviderTelephone varchar(15) )
Select *
from #temp_MemberInfo
Inner Join #temp_ProviderInfo on #temp_ProviderInfo.RecID = #temp_MemberInfo.RecID
The alternative I can think of would be to use an existing primary key in the date base but I would have to join an extra table in the update statements. Is this better from a performance standpoint? Are there other alternatives I'm not considering?

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]

Computed persisted column does not pick index and shows conversion warning in SQL Server 2016 sp1-cu4

I created PK based on identity column a computed persisted column as
('P'+ RIGHT('000000000' + CONVERT([VARCHAR](8), [ID], (0)), (7))) PERSISTED
I created both tables, in the same way, a persisted columns. When I tried to join both persisted columns on inner join, it does not pick the index and warning is being shown
Type conversion expression convert(varchar(8), id, 0) may effect cardinality estimate in version Microsoft SQL Server 2016 -sp1cu4
Table #1:
create table dbo.master_designation
(
id int identity(1,1) not null,
dept_code varchar(8) not null,
user_type_code varchar(8) not null,
desig_code as ('P'+ RIGHT('0000000' + CONVERT([VARCHAR](8), [ID], (0)), (7))) PERSISTED,
name varchar(30) not null,
shortname varchar(30) not null
) on primary
Create index:
create nonclustered index idx2
on master_designation (desig_code);
Table #2:
create table dbo.mapping_employee_designation
(
id int identity(1,1) not null,
emp_code varchar(8) not null,
dept_code varchar(8) not null,
desig_code as ('P'+ RIGHT('0000000' + CONVERT([VARCHAR](8), [ID], (0)), (7))) PERSISTED,
location_code varchar(5) null,
report_to varchar(8) null,
active bit not null
) on primary
Create index
create nonclustered index idx1
on mapping_employee_designation (desig_code);

SQL Query to build a delimited string for a column for each distinct id in a table [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 6 years ago.
I have 4 tables that have 2 columns each.
'Column 1' is the 'One'
'Column 2' is the 'Many'
Column 1 has several different ID's that i need to group somehow and build a delimited string of all the 'Columns 2' values.
I need to do this for every distinct 'Column 1' value.... is this possible?
So for example i have this table..
DECLARE #tblDeadsData TABLE (
[ID] INT IDENTITY(1,1) NOT NULL,
[ContainerID] INT NULL,
[DeadsID] INT NULL
)
It is already populated with data, i need to build a delimited string of ALL the [DeadsID] for each [ContainerID], and then these delimited string need to be placed into this table (the DeadsDataTable Data goes into the tblLastMerge.DeadsIDList in this case)..
CREATE TABLE tblLastMerge(
[ID] INT IDENTITY(1,1) NOT NULL,
[FeedLotID] INT NULL,
[ContainerID] INT NULL,
[ContainerName] VARCHAR(40) NULL,
[IsMergeTargetContainer] BIT NULL,
[PurchaseIDList] VARCHAR(1000) NULL,
[DeadsIDList] VARCHAR(1000) NULL,
[RailersIDList] VARCHAR(1000) NULL,
[FeedBillIDList] VARCHAR(1000) NULL
)
***************************EDIT*********************************
in regards to the duplicate post.........Concatenation is not delimited!!!!!! no wonder when i did a search for my problem i did not see this post..... i do think you should link these 2 post though as i found an answer much more simplified compared to the (supposedly) original post
Thanks...... i found an answer
--table to hold the old deads data
DECLARE #tblDeadsData TABLE (
[ID] INT IDENTITY(1,1) NOT NULL,
[ContainerID] VARCHAR(10) NULL,
[DeadsID] VARCHAR(10) NULL
)
insert into #tbldeadsdata
values('1','2'),('1','3'),('1','4'),('2','2'),('2','3'),('2','4')
SELECT ContainerID, DeadsID = STUFF((SELECT N', ' + DeadsID
FROM #tblDeadsData AS p2
WHERE p2.ContainerID = p.ContainerID
ORDER BY DeadsID
FOR XML PATH(N'')), 1, 2, N'')
FROM #tblDeadsData AS p
GROUP BY ContainerID
ORDER BY ContainerID

Can CAST and CONVERT be used in a table creation

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)