Insert data into teable variable - sql

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

Related

Insert into a new Table in SQL gives error

Why am I getting an error?
--Q1
CREATE table Aorders (
Id INT IDENTITY NOT NULL,
CreatedDate Date NOT NULL,
BillingCountry varchar Not Null,
MerchId int Not null,
OrderStatus varchar Not null,
);
--Q2
select * from Aorders
--Q3 edited as suggested here but still get an error
INSERT INTO Aorders (CreatedDate, BillingCountry, MerchId, OrderStatus)
VALUES ('2001-01-01', 'Israel', 5 ,'Approved');
You must define the length of the varchar columns like:
CREATE table Aorders (
Id INT IDENTITY NOT NULL,
CreatedDate Date NOT NULL,
BillingCountry varchar(100) Not Null,
MerchId int Not null,
OrderStatus varchar(100) Not null,
);
From char and varchar (Transact-SQL):
When n isn't specified in a data definition or variable declaration
statement, the default length is 1
When doing an insert, the best practice is to list all the columns explicitly and to use standard formats for dates:
INSERT INTO Aorders (CreatedDate, BillingCountry, MerchId, OrderStatus)
VALUES ('2001-01-01', 'Israel', 5 ,'Approved');
Your specific error is because you have four values in the VALUES() list but there are five columns in the table.
You have not done your query properly. I think you want the ID to auto increment ,but you haven't declare that. Make changes as below:
CREATE table Aorders ( Id INT IDENTITY NOT NULL
,CreatedDate Date NOT NULL
,BillingCountry varchar Not Null
,MerchId int Not null
,OrderStatus varchar Not null);
Now enter the query as you have inserted. And also make sure proper date formats from documentation.

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]

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)

Insert Data Into three joined tables using a stored procedure

I have three tables [PublicationNotice], [PublicationNoticeClient] and [PublicationNoticeInvoice].
Table1 have one-to-one relation with table2 and table3.
I am using a stored procedure to insert data into the tables. My form consists of all attributes from table1, table2 and table3.
My problem is, when I Submit data into these three tables it inserts all data accept table2_id and table3_id in table1.
HINT: I am using ASP .Net and MSSQL
My stored procedure looks like this:
CREATE procedure [dbo].[AddUpdatePublicationNotice]
#ID bigint = NULL,
#Title varchar(max)= NULL,
#NewspaperName varchar(50) =NULL,
#Cities varchar(max)= NULL,
#PublicationSize varchar(8) =NULL,
#PublicationDate date =NULL,
#PublicationType varchar(50)= NULL,
#NewspaperPageNo smallint= NULL,
#Colored bit= NULL,
#CaseNature varchar(15)= NULL,
#ImagePath varchar(max)= NULL,
#ClientId bigint =NULL,
#InvoiceId bigint= NULL,
#CreatedById bigint = NULL,
#EditedById bigint= NULL,
#EditedDate datetime =NULL,
--******************************************--
#ClientName varchar(max)= NULL,
#ClientType varchar(50)= NULL,
#ClientContactPerson varchar(max)= NULL,
#ClientAddress varchar(max)= NULL,
#ClientCity varchar(50) =NULL,
#ClientCountry varchar(50)= NULL,
--******************************************--
#InvoiceDate date= NULL,
#InvoiceTotalAmount bigint= NULL,
#InvoicePaymentRecievedDate date= NULL,
#InvoiceChequeNo bigint= NULL,
#InvoiceBankName varchar(50)= NULL
--******************************************--
AS
Insert into PublicationNotice (
[Title]
,[NewspaperName]
,[Cities]
,[PublicationSize]
,[PublicationDate]
,[PublicationType]
,[NewspaperPageNo]
,[Colored]
,[CaseNature]
,[ImagePath]
,[ClientId]
,[InvoiceId]
,CreatedById
)Values(
#Title
,#NewspaperName
,#Cities
,#PublicationSize
,#PublicationDate
,#PublicationType
,#NewspaperPageNo
,#Colored
,#CaseNature
,#ImagePath
,#ClientId
,#InvoiceId
,#CreatedById)
insert into [dbo].[PublicationNoticeClient] (
[Name]
,[Type]
,[ContactPerson]
,[Address]
,[City]
,[Country]
,[CreatedById])
Values(#ClientName
,#ClientType
,#ClientContactPerson
,#ClientAddress
,#ClientCity
,#ClientCountry
,#CreatedById)
Insert Into [dbo].[PublicationNoticeInvoice] (
[Date]
,[TotalAmount]
,[PaymentRecievedDate]
,[ChequeNo]
,[BankName]
,[CreatedById])
Values (
#InvoiceDate
,#InvoiceTotalAmount
,#InvoicePaymentRecievedDate
,#InvoiceChequeNo
,#InvoiceBankName
,#CreatedById)
GO
I know I can first insert table2 and table3 values and then select the last inserted values from table2 and table3 (that are table2_id and table3_id) and then insert them into table1
Is there any other fast way to insert data like this ???
You can use ##IDENTITY , SCOPE_IDENTITY, IDENT_CURRENT or OUTPUT methods to retrieve last ID. The Output is the only secure one.
You need to insert into a table variable first and then query it
create table table1(
id int identity(1,1),
id_table2 int,
id_table3 int);
create table table2 (
id int identity(100,1),
val varchar(20));
create table table3 (
id int identity(200,1),
val varchar(20));
declare #varTable2 table (LastID int);
declare #varTable3 table (LastID int);
insert into table2
output inserted.id into #varTable2 values ('a');
insert into table3
output inserted.id into #varTable3 values ('a');
insert into table1 (id_table2, id_table3) values
( (select LastID from #varTable2),
(select LastID from #varTable3)
);
select * from table1
--You need to declare two variables to get identity values from table 2 and table 3 As
DECLARE #table2_identity AS INT
DECLARE #table3_identity AS INT
--After insert in Table 2 set table2_identity variable as follows
SET #table2_identity = SELECT SCOPE_IDENTITY()
--After insert in Table 3 set table3_identity variable as follows
SET #table3_identity = SELECT SCOPE_IDENTITY()
--Then assign those variable values in insert query of Table 1

Insert multiple records using stored procedure

I have two tables
emplyoee (first table)
id primary key auto increment
emp_name varchar
student(second table)
id foriegnkey emplyoee.id
st_name varchar
I want to insert multiple student records for a single employeeid . My code is attached here , but this use to only one student record update. How can I write stored procedure for this need.
I am new with SQL server and stored procedure.
Could you please help me?
create procedure empst_Sp
#emp_name varchar(50),
#st_name varchar(50)
as
begin
insert into emplyoee (emp_name) values (#emp_name)
insert into student(id,st_name) values(SCOPE_IDENTITY(),#st_name)
end
For your case, you can try this code above ( I'm using XML parameter type)
CREATE PROCEDURE EmployeeIns
#EmployeeName NVARCHAR(50),
#Students XML
AS
/*
#Students : <Students>
<Student Name='Studen 1'/>
<Student Name='Studen 1'/>
</Students>
*/
BEGIN
DECLARE #StudenTable TABLE(Name NVARCHAR(50))
DECLARE #EmployeeId INT
INSERT INTO #StudenTable
SELECT Tbl.Col.value('#Name', 'NVARCHAR(50)')
FROM #Students.nodes('//Student') Tbl(Col)
INSERT INTO Emplyoee VALUES(#EmployeeName)
SET #EmployeeId = SCOPE_IDENTITY()
INSERT INTO Student
SELECT #EmployeeId, Name FROM #StudenTable
END
Update 1 :
Your table design should be look like this :
CREATE TABLE [dbo].[Emplyoee](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](150) NULL,
CONSTRAINT [PK_Emplyoee] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
CREATE TABLE [dbo].[Student](
[EmployeeId] [int] NULL,
[Name] [nvarchar](150) NULL,
[Id] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
The execute code :
EXEC EmployeeIns #EmployeeName='trungtin1710', #Students = '<Students><Student Name="Studen 1"/><Student Name="Studen 1"/></Students>'
All you need is a local variable in which you can set the value retrieved from Scope_Identity:-
CREATE PROCEDURE empst_Sp
#emp_name varchar(50),
#st_name varchar(50)
AS
BEGIN
DECLARE #id INT
INSERT INTO emplyoee (emp_name) VALUES (#emp_name)
set #id = SCOPE_IDENTITY()
INSERT INTO student(id,st_name) VALUES (#id,#st_name)
END
As I understand:
If emplyoee with #emp_name is already exists then insert student records with ID of the emplyoee, if there is not any emplyoee with #emp_name then need to insert new emplyoee and student with ID of the new emplyoee. Yes?
CREATE PROCEDURE empst_Sp
#emp_name varchar(50),
#st_name varchar(50)
AS
BEGIN
DECLARE #EmplyoeeId int
SET #EmplyoeeId = NULL
select #EmplyoeeId = id
from emplyoee
where emp_name = #emp_name
IF #EmplyoeeId IS NULL
BEGIN
insert into emplyoee (emp_name) values (#emp_name)
SET #EmplyoeeId = SCOPE_IDENTITY()
END
insert into student(id, st_name) values(#EmplyoeeId, #st_name)
END