I am insert bulk of records how to get all those Id's from inserted tables.
I want to use all those ids as forgein keys and insert into another table
INSERT INTO [dbo].[BudCustomers]
([LegalName]
,[EffectiveDate]
,[LawsonCustomerNumber]
,[ChangeReason]
,[ImportedRecord]
,[VersionID]
,[StatusID]
,[CreatedDate]
,[CreatedUserID]
,[LastModifiedDate]
,[LastModifiedUserID]
,[CustomerGroupID])
SELECT CustomerName
,'1900-01-01 00:00:00.000'
, CASE WHEN PATINDEX('%[0-9]%', CustomerName) > 0
THEN REPLACE(SUBSTRING(CustomerName, PATINDEX('%[0-9]%', CustomerName),
LEN(CustomerName)), ')', '')
ELSE 0 END
,''
,1
,1
,1
,GETDATE()
,'Import'
,GETDATE()
,'Import'
,NULL
FROM External_Blk_Itm_Contracts
WHERE TerminalName NOT IN (SELECT MBFTERMINALNAME FROM budterminals)
Use OUTPUT clause:
CREATE TABLE #temp (CustomerId <datatype> );
INSERT INTO [dbo].[BudCustomers]
([LegalName]
,[EffectiveDate]
,[LawsonCustomerNumber]
,[ChangeReason]
,[ImportedRecord]
,[VersionID]
,[StatusID]
,[CreatedDate]
,[CreatedUserID]
,[LastModifiedDate]
,[LastModifiedUserID]
,[CustomerGroupID])
OUTPUT inserted.CustomerId
INTO #temp
SELECT CustomerName
,'1900-01-01 00:00:00.000'
, CASE
WHEN PATINDEX('%[0-9]%', CustomerName) > 0
THEN REPLACE(SUBSTRING(CustomerName, PATINDEX('%[0-9]%', CustomerName),
LEN(CustomerName)), ')', '') ELSE 0 END
,''
,1
,1
,1
,GETDATE()
,'Import'
,GETDATE()
,'Import'
,NULL
FROM External_Blk_Itm_Contracts
WHERE TerminalName NOT IN (SELECT MBFTERMINALNAME FROM budterminals)
SELECT *
FROM #temp;
Related
This question already has an answer here:
TSQL PIVOT MULTIPLE COLUMNS
(1 answer)
Closed 4 years ago.
Below is the data rows I have:
ID Code OtherCol
7 Code1 NULL
7 code2 NULL
2 unk NULL
4 unk NULL
3 Code2 NULL
3 Code3 NULL
3 Code5 Other1
5 Code4 NULL
5 Code5 Other2
I am trying get this displayed as
ID name1 name2 name3 name4 name5 nameunk Othername
2 unk
3 code2 code3 code5 Other1
4 unk
5 code4 code5 Other2
7 code1 code2
I was able to pivot the first column but having a problem pivoting the second one.
And also there is a name for a given code, but the value under OtherCol are random.
I recommend conditional aggregation:
select id,
max(case when code = 'code1' then code end) as name1,
max(case when code = 'code2' then code end) as name2,
max(case when code = 'code3' then code end) as name3,
max(case when code = 'code4' then code end) as name4,
max(case when code = 'code5' then code end) as name5,
max(case when code = 'unk' then code end) as nameunk,
max(othercol) as othercol
from t
group by id;
This is full working example. You can change it a little bit to match your real data.
CREATE TABLE #DataSource
(
[ID] INT
,[Code] VARCHAR(12)
,[OtherCol] VARCHAR(12)
);
INSERT INTO #DataSource ([ID], [Code], [OtherCol])
VALUES (7, 'Code1', NULL)
,(7, 'code2', NULL)
,(2, 'Unk', NULL)
,(4, 'Unk', NULL)
,(3, 'Code2', NULL)
,(3, 'Code3', NULL)
,(3, 'Code5', 'Other1')
,(5, 'Code4', NULL)
,(5, 'Code4', 'Other2');
DECLARE #DynammicTSQLStatement NVARCHAR(MAX)
,#DynamicPIVOTColumns NVARCHAR(MAX);
SET #DynamicPIVOTColumns = STUFF
(
(
SELECT ',[' + CAST([value] AS VARCHAR(12)) + ']'
FROM
(
SELECT 0
,DENSE_RANK() OVER (ORDER BY [Code])
,REPLACE([Code], 'Code', 'name')
FROM #DataSource
WHERE [Code] IS NOT NULL
UNION
SELECT 1
,1
,'OtherCol'
) DS ([GroupID],[RowID], [value])
ORDER BY [GroupID], [RowID]
FOR XML PATH('') ,TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
SET #DynammicTSQLStatement = N'
SELECT *
FROM
(
SELECT [ID]
,[Code]
,REPLACE([Code], ''Code'', ''name'')
FROM #DataSource
UNION ALL
SELECT [ID]
,[OtherCol]
,''OtherCol''
FROM #DataSource
) DS ([ID], [value], [column])
PIVOT
(
MAX([value]) FOR [column] IN (' + #DynamicPIVOTColumns + ')
) PVT';
EXEC sp_executesql #DynammicTSQLStatement;
DROP TABLE #DataSource;
--PIVOT THE TABLE
select ID,[code1],[code2], [code3],[code4],[code5],[Unk]
into #resPivot
from
(
select ID, code
from tblTest
) src
pivot
(
max(code)
for code in ([code1], [code2], [code3],[code4],[code5],[Unk])
) piv;
--FIND ALL COLS WHERE OTHER COLUMN have value row 3,5 in your example
SELECT * INTO #distinct FROM tblTest where tblTest.otherCol IS NOT NULL
--PIVOTED RESULT WITH ABOVE TABLE
select distinct #resPivot.ID,[code1], [code2], [code3],[code4],[code5],[Unk],#distinct.otherCol
into #otherCol
from #resPivot inner join #distinct
on #distinct.id = #resPivot.id
--THIS IS PIVOTED RESULT WITH ALL RESULTS THAT HAS NO OTHER COL VALUE UNION with OTHER CALL VALUE
select distinct #resPivot.ID,[code1], [code2], [code3],[code4],[code5],[Unk],tblTest.otherCol
from #resPivot inner join tblTest
on tblTest.id = #resPivot.id
WHERE otherCol IS NULL and tblTest.ID NOT IN (SELECT ID FROM #otherCol)
UNION ALL
Select * from #otherCol
--DROP TEMP TABLES
Drop Table #resPivot
Drop Table #distinct
Drop Table #otherCol
A little simpler and faster version
I am trying to transpose data in a SQL Server table with one row of data but with several columns, all into one column along with their respective column headers.
Original Data Table:
**TABLE Column Names:** Id, ColumnA , ColumnB , ColumnC , StartDate
**Data:** 1, 'aa' , 'bb' , 'cc', 2016-10-10
Required Format of Data:
**ColumnName Values**
Id 1
ColumnA aa
ColumnB bb
ColumnC cc
StartDate 2016-10-10
CREATE DATABASE ToDelete
GO
USE [ToDelete]
GO
CREATE TABLE [dbo].[sourceData](
[id] [int] NULL,
[ColumnA] [varchar](50) NULL,
[ColumnB] [varchar](50) NULL,
[ColumnC] [varchar](50) NULL,
[StartDate] [datetime] NULL
)
GO
INSERT [dbo].[sourceData] ([id], [ColumnA], [ColumnB], [ColumnC], [StartDate], [EndDate]) VALUES (1, 'aa', N'bb', N'cc', GETDATE())
GO
The query I am using to pull the table column names is:
SELECT c.name
FROM sys.tables t
JOIN sys.columns c
ON t.object_id = c.object_id
WHERE t.name = 'sourceData'
Your help would be appreciated.
Thank you
Here is an option that may help you create something more like an EAV structure
Example
Declare #YourTable Table ([Id] varchar(50),[ColumnA] varchar(50),[ColumnB] varchar(50),[ColumnC] varchar(50),[StartDate] date)
Insert Into #YourTable Values
(1,'aa','bb','cc','2016-10-10')
Select A.ID
,C.*
From #YourTable A
Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
Cross Apply (
Select Field = a.value('local-name(.)','varchar(100)')
,Value = a.value('.','varchar(max)')
From B.XMLData.nodes('/row') as C1(n)
Cross Apply C1.n.nodes('./#*') as C2(a)
Where a.value('local-name(.)','varchar(100)') not in ('ID','OtherColumnsTo','Exclude')
) C
Returns
ID Field Value
1 ColumnA aa
1 ColumnB bb
1 ColumnC cc
1 StartDate 2016-10-10
Try the Following Solution, I have Referred from the following article to write this query:
https://www.red-gate.com/simple-talk/sql/t-sql-programming/questions-about-pivoting-data-in-sql-server-you-were-too-shy-to-ask/
USE [ToDelete]
GO
DECLARE #sql AS NVARCHAR(2000);DECLARE #col AS NVARCHAR(2000);
DECLARE #col1 AS NVARCHAR(2000);
SELECT #col = ISNULL(#col + ', ', '') +
concat('cast(',QUOTENAME(column_name),'as nvarchar(max))',' ',
QUOTENAME(column_name) ),#col1=ISNULL(#col1 + ', ', '') +QUOTENAME(column_name)
FROM (SELECT DISTINCT column_name FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='sourceData') AS Colname;
SET #sql =N'select columnname,[values] from (select '+#col+ ' from dbo.sourceData) as D Unpivot
([values] for columnname in (' + #col1 + '))
as unpiv'
EXEC sp_executesql #sql;
Simply use Union all like this:
select Id,'ColumnA' columnName, ColumnA [Values]
from t
union all
select Id,'ColumnB' , ColumnB
from t
union all
select Id,'ColumnC' , ColumnC
from t
union all
select Id,'StartDate' , cast(StartDate as nvarchar(max))
from t;
SQL Fiddle Demo
Additional variant using unpivot:
dataset
DECLARE #YourTable TABLE
([Id] VARCHAR(10),
[ColumnA] VARCHAR(10),
[ColumnB] VARCHAR(10),
[ColumnC] VARCHAR(10),
[StartDate] DATE
);
INSERT INTO #YourTable
VALUES
(1, 'aa', 'bb', 'cc', '2016-10-10'),
(2, 'cc', 'dd', 'zz', '2016-10-11');
query
SELECT Id,
Field,
[Value]
FROM
( SELECT Id,
ColumnA,
ColumnB,
ColumnC,
CONVERT(VARCHAR(10), StartDate) AS StartDate
FROM #YourTable
) AS t UNPIVOT([Value] FOR [Field] IN ( ColumnA,
ColumnB,
ColumnC,
StartDate)) up;
I'm getting this error from the below T-SQL query.
Error message:
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '101'
Can anyone spot where the error here is? Using Management Studio / SQLServerExpress The desired result is a new record inserted or an existing one update.
Below is my query:
IF EXISTS (SELECT * FROM Product WHERE ProductID = 101)
UPDATE Product SET
ProductID = 101 , InsurerID = 1, CategoryID =1, Name = 'Landlord',
[description] ='Allianz Landlord', label = 'NULL', AssumptionRef ='NULL',
QuoteProviderKey ='A75',AccidentalDamageCover =0, ProductBenefitGroupID = 11,
IsAvailableToBuy =1,IsAvalableToDisplay =0,PercentageContentsCover ='NULL',
ProductPolicyView ='NULL', ProductFee =NULL
WHERE ProductID = 101
ELSE
INSERT INTO Product
VALUES 101,1,1,'Landlord','Allianz Landlord','NULL','NULL','A75',0,11,1,0,'NULL','NULL',NULL
WHERE ProductID = 101
Your INSERT statement has a WHERE clause with VALUES set, which isn't valid:
INSERT INTO Product
VALUES 101
,1
,1
,'Landlord'
,'Allianz Landlord'
,'NULL'
,'NULL'
,'A75'
,0
,11
,1
,0
,'NULL'
,'NULL'
,NULL
WHERE ProductID = 101
You are also missing () around the VALUES section, as well as the columns listed out (though, that won't give an error, but you should get in the habit of explicitly listing the columns)
Your statement should look like this:
INSERT INTO Product
(
ProductID
,InsurerID
,CategoryID
,NAME
,[description]
,label
,AssumptionRef
,QuoteProviderKey
,AccidentalDamageCover
,ProductBenefitGroupID
,IsAvailableToBuy
,IsAvalableToDisplay
,PercentageContentsCover
,ProductPolicyView
,ProductFee
)
VALUES
(
101
,1
,1
,'Landlord'
,'Allianz Landlord'
,'NULL'
,'NULL'
,'A75'
,0
,11
,1
,0
,'NULL'
,'NULL'
,NULL
)
Another thing to question is why you're using string 'NULL' values. If you're intending these fields to be NULL, they should be NULL and not 'NULL'
Replace the last where clause because according to your scenario you dont need where in INSERT statement
try running this one
IF EXISTS (SELECT * FROM Product WHERE ProductID = 101) UPDATE Product SET ProductID = 101 , InsurerID = 1, CategoryID =1, Name = 'Landlord', [description] ='Allianz Landlord', label = 'NULL', AssumptionRef ='NULL', QuoteProviderKey ='A75',AccidentalDamageCover
=0, ProductBenefitGroupID = 11, IsAvailableToBuy =1,IsAvalableToDisplay =0,PercentageContentsCover ='NULL', ProductPolicyView ='NULL', ProductFee =NULL WHERE ProductID = 101 ELSE INSERT INTO Product VALUES 101,1,1,'Landlord','Allianz Landlord','NULL','NULL','A75',0,11,1,0,'NULL','NULL',NULL
You forgot the begin end
IF (.....)
BEGIN
END
ELSE
BEGIN
END
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)
I have a table like this
Declare #Temp Table(Data VarChar(20))
Insert Into #Temp Values('F_200_100_')
Insert Into #Temp Values('F_50_')
Insert Into #Temp Values('F_30_')
Insert Into #Temp Values('F_50_10')
Insert Into #Temp Values('F_100_')
Insert Into #Temp Values('F_20_')
I want my output to be distinct values of the numbers extracted from data column
20
30
50
100
200
I have tried using patindex but I am looking for ideas
tried this
select
Left(
SubString(Data, PatIndex('%[0-9]%', Data), 8000),
PatIndex('%[^0-9]%', SubString(Data, PatIndex('%[0-9]%', Data), 8000) + 'X')-1
)
from #temp
Reference
http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server
try this:
DECLARE #YourTable table (RowID int, Layout varchar(200))
INSERT INTO #YourTable
select ROW_NUMBER() over (order by (select 0)) as rn,replace(RIGHT(data,len(data)-CHARINDEX('_',data,1)),'_',',') from temptab
;WITH SplitSting AS
(
SELECT
RowID,LEFT(Layout,CHARINDEX(',',Layout)-1) AS Part
,RIGHT(Layout,LEN(Layout)-CHARINDEX(',',Layout)) AS Remainder
FROM #YourTable
WHERE Layout IS NOT NULL AND CHARINDEX(',',Layout)>0
UNION ALL
SELECT
RowID,LEFT(Remainder,CHARINDEX(',',Remainder)-1)
,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(',',Remainder))
FROM SplitSting
WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)>0
UNION ALL
SELECT
RowID,Remainder,null
FROM SplitSting
WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)=0
)
SELECT distinct cast(part as int) FROM SplitSting where len(part) > 0 order by cast(part as int)