Insert value into table - sql

I have below SQL query, am trying to insert data into test table, but I got another requirement that I need to insert the employee number along with his/her name.
Example
firstname : 71853-osama
My question is, How I can insert two values into one attribute
I tried this
badgeno +'-'+ convert(nvarchar(100),cEmpname) as cEmpname
but it didn't work
insert into PT (
[FirstName]
,[LastName]
,[FirmID]
,[Note]
,[City]
,[ThirdPartyId]
,[RegisteredBy]
,[Registered]
,[LastUpdatedBy]
,[LastUpdated]
)
SELECT distinct
convert(nvarchar(100),cEmpname) as cEmpname
,convert(nvarchar(100),cJobTitle) as cJobTitle
,'2' as FirmID
,convert(nvarchar(500),sort1) as sort1
,convert(nvarchar(255),cnationality) as cnationality
, badgeno as 'ThirdPartyId'
,'admin' as RegisteredBy
,CURRENT_TIMESTAMP as Registered
,'admin' as LastUpdatedBy
, CURRENT_TIMESTAMP as LastUpdated
FROM [TrailBlazerNG].[dbo].[payper] where lactive = '1'
and not exists ( select 1 from PT where payper.badgeno = PT.ThirdPartyId)

Try below.
insert into PT ([FirstName],[FirmID],[Note],[City],[ThirdPartyId],[RegisteredBy],[Registered],[LastUpdatedBy],[LastUpdated])
SELECT distinct
convert(nvarchar(100),badgeno)+'-'+convert(nvarchar(100),cEmpname) as cEmpname
,convert(nvarchar(100),cJobTitle) as cJobTitle
,'2' as FirmID
,convert(nvarchar(500),sort1) as sort1
,convert(nvarchar(255),cnationality) as cnationality
, badgeno as 'ThirdPartyId'
,'admin' as RegisteredBy
,CURRENT_TIMESTAMP as Registered
,'admin' as LastUpdatedBy
, CURRENT_TIMESTAMP as LastUpdated
FROM [TrailBlazerNG].[dbo].[payper] where lactive = '1'
and not exists ( select 1 from PT where payper.badgeno = PT.ThirdPartyId)

Related

UNION and MIN/MAX with Grouping and Odd Date Request

This is a new version of my question, since it seems to be confusing. Sorry. I figured it out. See the code if you're interested. Notes to solve are in there. Thanks for your help!
I got it to work this far, but the OriginaionL (L is for Little and B is for Big) is not correct. It's taking the correct date but not Origination.
CREATE TABLE MyTable
(
LoadTagID INT,
EnteredDateTime datetime,
JobNumber VARCHAR(50),
Origination VARCHAR(50)
)
INSERT INTO MyTable VALUES
(1, '2015-02-09 00:00:00.00', 11111, 'Here')
,(2, '2015-02-09 00:00:00.00', 22222, 'There')
,(3, '2016-03-09 00:00:00.00', 11111, 'Outside')
,(4, '2016-08-09 00:00:00.00', 12578, 'Anywhere')
,(252, '2017-06-29 00:00:00.00', 12345, 'Here')
,(253, '2017-08-01 00:00:00.00', 99999, 'There')
,(254, '2017-08-04 00:00:00.00', 12345, 'Outside')
,(255, '2017-08-09 00:00:00.00', 12345, 'Anywhere')
,(256, '2017-08-10 00:00:00.00', 99999, 'Anywhere')
,(257, '2017-08-10 00:00:00.00', 123456, 'Anywhere')
,(258, '2017-08-11 00:00:00.00', 123456, 'Over Yonder')
,(259, '2017-08-13 00:00:00.00', 99999, 'Under The Bridge')
--Select * From MyTable
CREATE TABLE #LTTB1 --MAX
(
LoadTagID varchar(50),
JobNumber varchar(50),
EnteredDateTime varchar(50),
Origination varchar(50)
)
CREATE TABLE #LTTB2 --MIN
(
LoadTagID varchar(50),
JobNumber varchar(50),
EnteredDateTime varchar(50),
Origination varchar(50)
)
CREATE TABLE #LTTB3
(
LoadTagIDL varchar(50),
JobNumberL varchar(50),
EnteredDateTimeL
varchar(50),
OriginationL varchar(50)
, LoadTagID varchar(50),
JobNumber varchar(50),
EnteredDateTime varchar(50),
Origination varchar(50)
)
INSERT INTO #LTTB1
SELECT
MAX(LoadTagID) AS LoadTagID,
JobNumber,
MAX(EnteredDateTime) AS EnteredDateTime,
MAX(Origination) AS Origination
FROM MyTable
WHERE CONVERT (Date, EnteredDateTime) >= CONVERT (Date, GETDATE()-10) --Gets the last 10 days.
GROUP BY JobNumber ORDER BY JobNumber
INSERT INTO #LTTB2
SELECT MIN(LoadTagID) AS LoadTagIDL,
JobNumber AS JobNumberL,
MIN(EnteredDateTime) AS EnteredDateTimeL,
MAX(Origination) AS OriginationL --MAX! This needed to be max!! Why?
FROM MyTable
Where CONVERT (Date, EnteredDateTime) >= CONVERT (Date, GETDATE()-60) --Goes further back in case one is a long.
GROUP BY JobNumber ORDER BY JobNumber
INSERT INTO #LTTB3
SELECT L.LoadTagID AS LoadTagIDL
, L.JobNumber AS JobNumberL
, L.EnteredDateTime AS EnteredDateTimeL
, L.Origination AS OriginationL
, B.LoadTagID, B.JobNumber, B.EnteredDateTime, B.Origination
FROM #LTTB1 B --MAX
INNER JOIN #LTTB2 L ON B.JobNumber = L.JobNumber
Select * From #LTTB3
So for JobNumber 12345 6/29 is correct, but it should be "Here" and not "Anywhere:
For 99999 everything is correct but for 8/1 it should be "There" and not Anywhere. That seems to be the middle value in the set. I'm so confused.
Does anyone know why it's grabbing that value? Thank you.
SELECT *
FROM mytable
WHERE LoadTagID=(SELECT MIN(LoadTagID)
FROM mytable)
OR LoadTagID=(SELECT MAX(LoadTagID)
FROM mytable);
query according to the output you want
CREATE TABLE MyTable
(
LoadTagID INT,
Date Date,
Job INT,
Origination VARCHAR(20)
)
INSERT INTO MyTable
VALUES(
252, '6/29/17', 12345, 'Here')
,(253, '8/1/17', 99999, 'There')
,(254, '8/4/17', 12345, 'Outside')
,(255, '8/8/17', 12345, 'Anywhere')
--SELECT * FROM MyTable
SELECT * INTO #Table1
FROM MyTable
WHERE LoadTagID IN (SELECT MIN(LoadTagID)
FROM MyTable)
SELECT * INTO #Table2
FROM MyTable
WHERE LoadTagID IN (SELECT MAX(LoadTagID)
FROM MyTable)
SELECT * INTO #T3
FROM ( SELECT * FROM #Table1 T1
UNION ALL
SELECT * FROM #Table2 T2
) A
SELECT #T3.Date,
#T3.Job,
#T3.LoadTagID,
#T3.Origination
FROM #T3
LEFT JOIN #Table1 T1
ON T1.Job=#T3.Job
WHERE T1.Job IS NOT NULL
INSERT INTO #LTTB1
SELECT
MAX(LoadTagID) AS LoadTagID,
JobNumber,
MAX(EnteredDateTime) AS EnteredDateTime,
MAX(Origination) AS Origination
FROM MyTable
WHERE CONVERT (Date, EnteredDateTime) >= CONVERT (Date, GETDATE()-10) --Gets the last 10 days.
GROUP BY JobNumber ORDER BY JobNumber
INSERT INTO #LTTB2
select LoadTagID
,JobNumber
,EnteredDateTime
,Origination from (
select *, ROW_NUMBER() Over(partition by jobnumber order by EnteredDateTime) l
from MyTable
Where CONVERT (Date, EnteredDateTime) >= CONVERT (Date, GETDATE()-60)
)lk
where lk.l=1
INSERT INTO #LTTB3
SELECT L.LoadTagID AS LoadTagIDL
, L.JobNumber AS JobNumberL
, L.EnteredDateTime AS EnteredDateTimeL
, L.Origination AS OriginationL
, B.LoadTagID, B.JobNumber, B.EnteredDateTime, B.Origination
FROM #LTTB1 B --MAX
INNER JOIN #LTTB2 L ON B.JobNumber = L.JobNumber
Select * From MyTable
Select * From #LTTB3
--I hope, your prob has been solved now..

SQL SCOPE_IDENTITY or OUTPUT with data from another table

I'm trying to get the ID of each row inserted from a mass insert and create a mapping table with an ID from my temp table #InsertedClients. I'm using the same temp table for the initial insert but the PDATClientID is not part of the insert. I can't seem to figure out how to do this correctly. When I inserting into the Client_Mapping table using SCOPE_IDENTITY it only grabs the ID from the first insert and puts it along with all of my PDATClientIDs. After doing a lot of Googling I believe I should be using OUTPUT, but can't seem to figure how to put the INSERTED.CLID for each record together with each PDATClientID. I should also say that I can't use a cursor there are too rows. Any help is greatly appreciated!
IF NOT EXISTS (
SELECT ID
FROM sysobjects
WHERE id = object_id(N'[Client_Mapping]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1
)
CREATE TABLE [Client_Mapping] (
ClientMappingID INT Identity(1, 1) NOT NULL
,PDATClientID INT NOT NULL
,CLID INT NOT NULL
,AUDITDATE DATETIME NOT NULL
,CONSTRAINT [PK_Client_Mapping] PRIMARY KEY (ClientMappingID)
)
-- Begin Inserts
SELECT
First_Name
,Middle_Name
,Last_Name
,CONVERT(DATETIME, Date_Of_Birth) AS DOB
,a.Address_Line as Address1
,a.Address_Line_2 as Address2
,a.Zip_Code as ZipCode -- ??? Do I need to account for zipcode + 4
,REPLACE(REPLACE(REPLACE(cphp.Number_Or_Address, '(', ''), ')', '-'), ' ', '') AS HomePhone
,REPLACE(REPLACE(REPLACE(cpcp.Number_Or_Address, '(', ''), ')', '-'), ' ', '') AS CellPhone
,cpem.Number_Or_Address AS EMAIL
,c.Client_ID as PDATClientID
,c.Action AS [ClientAction]
,ca.Action as [ClientAddressAction]
,a.Action AS [AddressAction]
,cphp.Action AS [HomePhoneAction]
,cpcp.Action AS [CellPhoneAction]
,cpem.Action AS [EmailAction]
INTO #InsertClients
FROM Client c
LEFT JOIN Client_Address ca ON ca.Client_ID = c.Client_ID
LEFT JOIN Address a ON a.Address_ID = ca.Address_ID
LEFT JOIN Client_Phone cphp ON cphp.Client_ID = c.Client_ID
AND cphp.Phone_Email_Type = 'HP'
AND cphp.Start_Date = (
SELECT MAX(Start_Date)
FROM Client_Phone
WHERE Client_ID = c.Client_ID
)
LEFT JOIN Client_Phone cpcp ON cpcp.Client_ID = c.Client_ID
AND cpcp.Phone_Email_Type = 'CP'
AND cpcp.Start_Date = (
SELECT MAX(Start_Date)
FROM Client_Phone
WHERE Client_ID = c.Client_ID
)
LEFT JOIN Client_Phone cpem ON cpem.Client_ID = c.Client_ID
AND cpem.Phone_Email_Type = 'EM'
AND cpem.Start_Date = (
SELECT MAX(Start_Date)
FROM Client_Phone
WHERE Client_ID = c.Client_ID
)
where c.action ='I'
BEGIN TRY
BEGIN TRAN
INSERT INTO [dbo].[Clients] (
[FName]
,[MiddleInitial]
,[LName]
,[DOB]
,[Address1]
,[Address2]
,[ZipCode]
,[HomePhone]
,[CellPhone]
,[Email]
,[AuditStaffID]
,[AuditDate]
,[DateCreated]
)
Select
First_Name
,CASE when Middle_Name = '' THEN NULL ELSE Middle_Name END
,Last_Name
,DOB
,Address1
,Address2
,ZipCode
,HomePhone
,CellPhone
,EMail
,496 AS [AuditStaffID]
,CURRENT_TIMESTAMP AS [AuditDate]
,CURRENT_TIMESTAMP AS [DateCreated]
FROM
#InsertClients
Where
[ClientAction] = 'I'
INSERT INTO [Client_Mapping]
(
PDATClientID
,CLID
,AUDITDATE
)
SELECT
PDATClientID
,SCOPE_IDENTITY()
,CURRENT_TIMESTAMP
FROM #InsertClients
COMMIT
END TRY
BEGIN CATCH
ROLLBACK
SELECT ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage
END CATCH
you have a hell of a code in your question I can explain you in few line how you can retrieve all the inserted ids.
Yes SCOPE_IDENTITY() gives you the last IDENTITY value generated by the identity column. In you case you will need to use a table variable to get all the generated Identity values during your insert
/* Declare a table Vairable */
DECLARE #NewValues TABLE (IDs INT);
/* In Your Insert Statement use OUTPUT clause */
INSERT INTO Table_Name (Column1,Column2,Column3,....)
OUTPUT inserted.Identity_Column INTO #NewValues (IDs)
SELECT Column1,Column2,Column3,....
FROM Table_Name2
/* Finally Select values from your table variable */
SELECT * FROM #NewValues
Your Query
In your case your insert statement should look something like ...
INSERT INTO [dbo].[Clients] (
[FName]
,[MiddleInitial]
,[LName]
,[DOB]
,[Address1]
,[Address2]
,[ZipCode]
,[HomePhone]
,[CellPhone]
,[Email]
,[AuditStaffID]
,[AuditDate]
,[DateCreated]
)
OUTPUT inserted.[FName], inserted.[MiddleInitial] ,.... INTO #TableVarible(First_Name,[MiddleInitial].....)
Select
First_Name
,CASE when Middle_Name = '' THEN NULL ELSE Middle_Name END
,Last_Name
,DOB
,Address1
,Address2
,ZipCode
,HomePhone
,CellPhone
,EMail
,496 AS [AuditStaffID]
,CURRENT_TIMESTAMP AS [AuditDate]
,CURRENT_TIMESTAMP AS [DateCreated]
FROM
#InsertClients
Where
[ClientAction] = 'I'
Solved the problem by using this example found here: http://sqlserverplanet.com/tsql/match-identity-columns-after-insert. The example from that site is below.
-- Drop temp tables if they already exist
IF OBJECT_ID('TempDB..#source', 'U') IS NOT NULL DROP TABLE #source;
IF OBJECT_ID('TempDB..#target', 'U') IS NOT NULL DROP TABLE #target;
IF OBJECT_ID('TempDB..#xref', 'U') IS NOT NULL DROP TABLE #xref;
GO
-- Create the temp tables
CREATE TABLE #source (id INT PRIMARY KEY IDENTITY(1, 1), DATA INT);
CREATE TABLE #target (id INT PRIMARY KEY IDENTITY(1, 1), DATA INT);
CREATE TABLE #xref (ROW INT PRIMARY KEY IDENTITY(1, 1), source_id INT, target_id INT);
GO
-- If xref table is being reused, make sure to clear data and reseed by truncating.
TRUNCATE TABLE #xref;
-- Fill source table with dummy data (even numbers)
INSERT INTO #source (DATA)
SELECT 2 UNION SELECT 4 UNION SELECT 6 UNION SELECT 8;
GO
-- Fill target table with dummy data (odd numbers) to simulate existing records
INSERT INTO #target (DATA)
SELECT 1 UNION SELECT 3 UNION SELECT 5;
GO
-- Insert source table data into target table. IMPORTANT: Inserted data must be sorted by the source table's primary key.
INSERT INTO #target (DATA)
OUTPUT INSERTED.id INTO #xref (target_id)
SELECT DATA
FROM #source
ORDER BY id ASC;
GO
-- Update the xref table with the PK of the source table. This technique is used for data not captured during the insert.
;WITH src AS (SELECT id, ROW = ROW_NUMBER() OVER (ORDER BY id ASC) FROM #source)
UPDATE x
SET x.source_id = src.id
FROM #xref AS x
JOIN src ON src.ROW = x.ROW;
GO
-- Verify data
SELECT * FROM #source;
SELECT * FROM #target;
SELECT * FROM #xref;
GO
-- Clean-up
IF OBJECT_ID('TempDB..#source', 'U') IS NOT NULL DROP TABLE #source;
IF OBJECT_ID('TempDB..#target', 'U') IS NOT NULL DROP TABLE #target;
IF OBJECT_ID('TempDB..#xref', 'U') IS NOT NULL DROP TABLE #xref;
GO

SQL Server 2008 - Stored inserted IDs in a variable table for another query use later

I have an INSERT query to insert multiple records and returns a set if CompanyID that inserted, and this query is working fine. I would like to stored those returned CompanyIDs into a table variable, so I can run another query after that using those CompanyIDs. I tried, but got stuck.
Please help.
-- Create a table variable
DECLARE #CompanyIDs TABLE
(
CompanyID INT NOT NULL
)
INSERT INTO #CompanyIDs -- STUCK right here and it failed
-- This INSERT query is working fine, and will return the CompanyIDs that inserted.
INSERT INTO [Apps].[dbo].[ERP_Company]
(
[Name]
,[Type]
,[ImportFrom]
,[InActiveFlag]
,[CreatedDate]
,[CreatedBy]
,[CompanyOwnerID]
,[ModifiedDate]
,[HQAddress]
,[HQCity]
,[HQState]
,[HQZip]
,[Type2]
,[Segment]
,[Industry]
)
output inserted.CompanyID
SELECT DISTINCT(Company) AS Company
, 'End-User'
, 'MarketingUpload'
, '0'
, GETDATE()
, '1581'
, '1581'
, GETDATE()
, [Address]
, City
, [State]
, ZipCode
, 'Customer'
, Segment
, Industry
FROM dbo.Import_CompanyContact icc
WHERE RefNum = 14
AND MatchFlag = 3
AND NOT Exists (SELECT * FROM dbo.ERP_Company
WHERE REPLACE(Name, '''', '') = REPLACE(icc.Company, '''', '')
)
OUTPUT inserted.CompanyID INTO #YourTable

how to insert multiple rows with check for duplicate rows in a short way

I am trying to insert multiple records (~250) in a table (say MyTable) and would like to insert a new row only if it does not exist already.
I am using SQL Server 2008 R2 and got help from other threads like SQL conditional insert if row doesn't already exist.
While I am able to achieve that with following stripped script, I would like to know if there is a better (short) way to do this as I
have to repeat this checking for every row inserted. Since we need to execute this script only once during DB deployment, I am not too much
worried about performance.
INSERT INTO MyTable([Description], [CreatedDate], [CreatedBy], [ModifiedDate], [ModifiedBy], [IsActive], [IsDeleted])
SELECT N'ababab', GETDATE(), 1, NULL, NULL, 1, 0
WHERE NOT EXISTS(SELECT * FROM MyTable WITH (ROWLOCK, HOLDLOCK, UPDLOCK)
WHERE
([InstanceId] IS NULL OR [InstanceId] = 1)
AND [ChannelPartnerId] IS NULL
AND [CreatedBy] = 1)
UNION ALL
SELECT N'xyz', 1, GETDATE(), 1, NULL, NULL, 1, 0
WHERE NOT EXISTS(SELECT * FROM [dbo].[TemplateQualifierCategoryMyTest] WITH (ROWLOCK, HOLDLOCK, UPDLOCK)
WHERE
([InstanceId] IS NULL OR [InstanceId] = 1)
AND [ChannelPartnerId] IS NULL
AND [CreatedBy] = 1)
-- More SELECT statements goes here
You could create a temporary table with your descriptions, then insert them all into the MyTable with a select that will check for rows in the temporary table that is not yet present in your destination, (this trick in implemented by the LEFT OUTER JOIN in conjunction with the IS NULL for the MyTable.Description part in the WHERE-Clause):
DECLARE #Descriptions TABLE ([Description] VARCHAR(200) NOT NULL )
INSERT INTO #Descriptions ( Description )VALUES ( 'ababab' )
INSERT INTO #Descriptions ( Description )VALUES ( 'xyz' )
INSERT INTO dbo.MyTable
( Description ,
CreatedDate ,
CreatedBy ,
ModifiedDate ,
ModifiedBy ,
IsActive ,
IsDeleted
)
SELECT d.Description, GETDATE(), 1, NULL, NULL, 1, 0
FROM #Descriptions d
LEFT OUTER JOIN dbo.MyTable mt ON d.Description = mt.Description
WHERE mt.Description IS NULL

sql query serial number

I have written a stored procedure in SQL Server 2000. I want a serial number for output table.
So when I run this stored proc I get this error:
An explicit value for the identity column in table
'#tmpSearchResults1' can only be specified when a column list is used
and IDENTITY_INSERT is ON.
I have tried with set IDENTITY_INSERT #tmpSearchResults1 on
Create Procedure dbo.usp_mobile_All_KeyWord(#searchkey varchar(30))
AS
CREATE TABLE #tmpSearchResults
(
property_id varchar(255),
property_number varchar(255),
auction_date_reason varchar(255)
)
INSERT INTO #tmpSearchResults
SELECT
p.property_id, p.property_number, p.auction_date_reason
FROM
Pr p
INNER JOIN
Au a ON p.auction_id = a.auction_id
INNER JOIN
PrAdd pa ON p.property_id = pa.property_id
INNER JOIN state AS s ON s.state_id=pa.state
where
(
(p.archive = 'N'
AND
a.show_on_site = 'Y'
AND
(
(
((p.auction_date >= CONVERT(datetime, CONVERT(varchar, GETDATE(), 103), 103) and (p.auction_date_reason is null or p.auction_date_reason = ''))
or
(p.auction_date <= CONVERT(datetime, CONVERT(varchar, GETDATE(), 103), 103) and ( p.auction_date_reason = 'Accepting Offers' )))
and
pa.property_address_type_id = 1 )) )
and
(state_abbreviation=#searchkey or s.state_name like '%'+''+ #searchkey +''+'%' or city like '%'+''+ #searchkey +''+'%' or pa.address1 like '%'+''+ #searchkey +''+'%'
or pa.address2 like '%'+''+ #searchkey +''+'%')
)
)
CREATE TABLE #tmpSearchResults1
(
i1 int identity,
property_id varchar(255),
property_number varchar(255),
auction_date_reason varchar(255)
)
insert into #tmpSearchResults1
select
property_id ,
property_number,
auction_date_reason
from #tmpSearchResults
order by
case when charindex(#searchkey,state) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,statename) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,city) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,address2) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,address1) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,short_description) >0 then 1000 else 0 end desc
select * from #tmpSearchResults1
Plz do help me
The error code is very very very clear.
The relevant portion is ...when a column list is used....
You need to specify your column list in the INSERT statement.
INSERT INTO #tmpSearchResults
(i1,
property_id,
property_number,
auction_date_reason)
SELECT
p.property_id, p.property_number, p.auction_date_reason
FROM...
First, there is a comma too much in the SELECT part of your second statement:
insert into #tmpSearchResults1
select
property_id ,
property_number,
auction_date_reason , <-- THIS ONE!!
from #tmpSearchResults
The last column of a SELECT statement must be without a comma.
So this would be correct:
insert into #tmpSearchResults1
select
property_id ,
property_number,
auction_date_reason
from #tmpSearchResults
Second, did you read this part of the error message?
An explicit value [...] can only be specified when a column list is used
The "column list" part means that you have to specify the columns in the INSERT part:
insert into #tmpSearchResults1
(property_id, property_number, auction_date_reason)
select
property_id ,
property_number,
auction_date_reason
from #tmpSearchResults
You can get away with not specifying the columns when the number of columns in the SELECT statement is the same as in the table in which they should be inserted (and if the data types match).
If one of these conditions is not met, you need to specify the columns because otherwise SQL Server doesn't know which value to insert into which column.