How to insert keyvalue as a row in table? - sql

I have table variable which contains records in terms of key,value pair of a table. where key is the column of table and value is the value for that column
below is table variable
DECLARE #Table TABLE(
FieldName varchar(100),
FieldValue varchar(max))
insert into #Table values('Title','NewFrom')
insert into #Table values('Points','4')
insert into #Table values('createdby','5')
I have above values in UsersInformation.This is physical table of sql server
has following column.
UserID int autoincrement(identity)
Title nvarchar(100),
Points int,
createdby int
I want that all values of #Table should be as a single row of UserInformation table.
How can be using sql server?

Have not tested but this should work
INSERT INTO UsersInformation (Title, Points, createdby)
SELECT Title, Points, createdby FROM (SELECT FieldName, FieldValue
FROM #Table) AS SourceTable
PIVOT (MAX(FieldValue) FOR FieldName IN ([Points], [Title], [createdby])) AS PivotTable;
Based on your comment you will need to add a key to your source #table
DECLARE #Table TABLE(
id int,
FieldName varchar(100),
FieldValue varchar(max))
insert into #Table values(1,'Title','NewFrom')
insert into #Table values(1,'Points','4')
insert into #Table values(1,'createdby','5')
insert into #Table values(2,'Title','NewFrom2')
insert into #Table values(2,'Points','44')
insert into #Table values(2,'createdby','55')
insert into #Table values(3,'Title','NewFrom3')
insert into #Table values(3,'Points','444')
Then you can run the query:
SELECT [Title], [Points], [createdby]
FROM #Table
PIVOT
(
max(FieldValue) FOR [FieldName] IN ([Title], [Points], [createdby])
) AS P

Related

Copy rows from the same table and update with different ID column and another column

I want copy the table and put different value on column Type= B and auto_increment id
If Id column is identity, you can achieve with below script:
insert into your_table ([parent_id], [order], [section], [name], [url], [type])
select [parent_id], [order], [section], [name], [url], 'B'
from your_table
where [type] = 'A'
If Id is not identity, use below logic:
-- find current max
declare #max int = (select max(ID) from your_table)
-- declare table var
declare #table table ([Id] int identity(1,1), [parent_id] nvarchar(50), [order] int, [section] nvarchar(50), [name] nvarchar(50), [url] nvarchar(50), [type] nvarchar(50))
-- insert values into this table
insert into #table
select [parent_id],
[order],
[section],
[name],
[url],
'B'
from your_table
where [type] = 'A'
-- then insert values from teble variable to your table
insert into your_table ([Id],[parent_id], [order], [section], [name], [url], [type])
select #max + [Id],
[parent_id],
[order],
[section],
[name],
[url],
[type]
from #table
You could use an insert select declaring the column you want insert and select the corresponding column from the same table and assigning a literal 'B' for the column type
insert into menu ( parent_id, order section, name, url, type)
select parent_id, order section, name, url, 'B'
from menu
where type ='A'

How to get The QueryString Without EXEC and Print Function

I have other table #table3 where the #qur will be stored and using that #qur i want to retrieve the data.
so it is possible to get data without set all query in other variable and execute this query directly.
this string of #qur not fixed it will different for different person.
and yes i use sql server 2010
CREATE TABLE #Table1
([Name] varchar(5), [DateVal] date, [TimeVal] time, [Item] varchar(5))
;
INSERT INTO #Table1
([Name], [DateVal], [TimeVal], [Item])
VALUES
('Lisa', '2015-04-21', '10:20:06', 'Item1'),
('John', '2015-04-21', '10:25:30', 'Item2'),
('Peter', '2015-03-18', '13:35:32', 'Item3'),
('Ralf', '2015-04-03', '09:26:52', 'Item4')
;
CREATE TABLE #Table2
([ID] int, [Name] varchar(5))
;
INSERT INTO #Table2
([ID],[Name])
VALUES
(1,'Lisa' ),
(2,'John' ),
(3,'Peter'),
(4,'Ralf')
;
DECLARE #qur VARCHAR(2000)='([Item] in (''Item1,Item2'')) and [Name]=''Lisa'') '
SELECT DateVal FROM #Table1
WHERE [Name] in (SELECT [Name] FROM #Table2)
AND #qur
Maybe You can use the query bellow in SQLCMD mode:
:setvar qur "and ([Item] in ('Item1','Item2')) and [Name]='Lisa' "
SELECT DateVal FROM #Table1
WHERE [Name] in (SELECT [Name] FROM #Table2)
$(qur)

Custom query assistance needed

I have 3 tables: (simplified for this question)
REQUIREMENTS : ID (PK), RequirementDescription
CUSTOMERS : ID (PK), CustomerName
CUSTOMER_REQUIREMENTS (join table): ID (PK), RequirementID (FK to REQUIREMENTS table), CustomerID (FK to CUSTOMERS table), DateCompleted
Question: I need to make a gridview in asp.net that basically shows the requirements on the left, all the customers as column headings and the DateCompleted as the "intersection". How can I do this?
For example:
Try following sql and replace temp tables with your table:
CREATE TABLE #REQUIREMENTS
(
ID INT,
RequirementDescription VARCHAR(100)
)
CREATE TABLE #CUSTOMERS
(
ID INT,
CustomerName VARCHAR(100)
)
CREATE TABLE #CUSTOMER_REQUIREMENTS
(
ID INT,
RequirementID INT,
CustomerID INT,
DateCompleted DATE
)
INSERT INTO #REQUIREMENTS VALUES (1,'Requirement1')
INSERT INTO #REQUIREMENTS VALUES (2,'Requirement2')
INSERT INTO #REQUIREMENTS VALUES (3,'Requirement3')
INSERT INTO #REQUIREMENTS VALUES (4,'Requirement4')
INSERT INTO #CUSTOMERS VALUES (1,'JOHN')
INSERT INTO #CUSTOMERS VALUES (2,'MARY')
INSERT INTO #CUSTOMERS VALUES (3,'BOB')
INSERT INTO #CUSTOMER_REQUIREMENTS VALUES (1,1,1,'2-2-2014')
INSERT INTO #CUSTOMER_REQUIREMENTS VALUES (1,2,1,'2-2-2014')
INSERT INTO #CUSTOMER_REQUIREMENTS VALUES (1,1,2,'2-2-2014')
INSERT INTO #CUSTOMER_REQUIREMENTS VALUES (1,2,2,'2-2-2014')
INSERT INTO #CUSTOMER_REQUIREMENTS VALUES (1,3,2,'2-2-2014')
INSERT INTO #CUSTOMER_REQUIREMENTS VALUES (1,4,2,'2-2-2014')
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
SELECT #ColumnName= ISNULL(#ColumnName + ',','') + QUOTENAME(CustomerName) FROM (SELECT DISTINCT CustomerName FROM #CUSTOMERS) AS Courses
SET #DynamicPivotQuery =
N'SELECT ReqID, ReqDes, ' + #ColumnName + '
FROM
(
SELECT
TEMP.ReqID,
TEMP.ReqDes,
TEMP.CusName,
CusReq.DateCompleted
FROM
(
SELECT
req.ID as ReqID,
req.RequirementDescription as ReqDes,
cus.ID as CusID,
cus.CustomerName as CusName
FROM
#REQUIREMENTS req,#CUSTOMERS cus
) AS TEMP
LEFT JOIN
#CUSTOMER_REQUIREMENTS as CusReq
ON
TEMP.ReqID = CusReq.RequirementID AND
Temp.CusID = CusReq.CustomerID
) AS TEMP1
PIVOT(MAX(TEMP1.DateCompleted)
FOR CusName IN (' + #ColumnName + ')) AS PVTTable'
EXEC sp_executesql #DynamicPivotQuery
DROP TABLE #CUSTOMER_REQUIREMENTS
DROP TABLE #CUSTOMERS
DROP TABLE #REQUIREMENTS

Assign multiple values to Table variable in SQL

DECLARE #ID INT
SET #ID = (select top 1 USER_REQ_JOB_ID
from T8504_USER_REQ_JOB
where JOB_GRP_ID = 160
order by LST_UPDT_TS desc)
SELECT INPUT_PARM_VAL_TX
from TBL_RPT_JOB_INPUT_PARAM
where USER_REQ_JOB_ID = #ID
This returns these results:
USA
USCC
6
7
2
These five records what I get I want to assign to five different variables to use in stored procedure.
I was trying with table variable like this :
declare #CID table (
Region Char(3)
,Segment Char(3)
,MasterContractId int
,ctcid int
,templateid int)
insert into #CID (Region,Segment,MasterContractId,ctcid,templateid)
But how to insert that 5 rows here?
INSERT INTO #CID
select * from
(
select
'Temp' + convert(char(1), row_number() over (order by (select 0))) as columnName,
INPUT_PARM_VAL_TX as Value
from TBL_RPT_JOB_INPUT_PARAM where USER_REQ_JOB_ID = #ID
) d
pivot
(
max(value)
for columnname in (Temp1, Temp2, Temp3, Temp4, Temp5)
) piv;
See if this helps.
Take a look at this fiddle for an example.
Courtesy:
Add row number to this T-SQL query
Efficiently convert rows to columns in sql server
EDIT: The sql adds an extra column to generate row numbers to use it as an extra column, which is pivoted as column heading.
it's really gross, but one way you could probably do it is this (though you'll need to apply it to your case):
http://sqlfiddle.com/#!6/d41d8/21507
declare #table TABLE (value varchar(50))
INSERT INTO #table
VALUES ('first')
INSERT INTO #table
VALUES ('second')
INSERT INTO #table
VALUES (3)
INSERT INTO #table
VALUES (4)
DECLARE #temp TABLE (id int identity(1,1), value varchar(50))
INSERT INTO #temp
SELECT [value]
FROM #table t
SELECT *
FROM #temp
DECLARE #CID TABLE (Region varchar(50), cont varchar(50), another int, andAnother int)
INSERT INTO #CID
(
Region,
cont,
another,
andAnother
)
VALUES
(
(SELECT value FROM #temp WHERE id = 1), -- Region - varchar
(SELECT value FROM #temp WHERE id = 2), -- cont - varchar
(SELECT value FROM #temp WHERE id = 3), -- another - int
(SELECT value FROM #temp WHERE id = 4) -- andAnother - int
)
SELECT * FROM #cid
note that i assumed you're using mssql, you did not specify

INSERT multiple rows and OUTPUT original (source) values

I would like to INSERT multpile rows (using INSERT SELECT), and OUTPUT all the new and old IDs into a "mapping" table.
How can I get the original ID (or any source values) in the OUTPUT clause? I don't see a way to get any source values there.
Here is a minimal code example:
-- create some test data
declare #t table (id int identity, name nvarchar(max))
insert #t ([name]) values ('item 1')
insert #t ([name]) values ('another item')
-- duplicate items, storing a mapping from src ID => dest ID
declare #mapping table (srcid int, [newid] int)
insert #t ([name])
output ?????, inserted.id into #mapping-- I want to use source.ID but it's unavailable here.
select [name] from #t as source
-- show results
select * from #t
select * from #mapping
My actual scenario is more complex, so for example I cannot create a temp column on the data table in order to store a "original ID" temporarily, and I cannot uniquely identify items by anything other than the 'ID' column.
Interesting question. For your example, a possible cheat is to depend on the fact that you are doubling the number of rows. Assuming that rows are never deleted and the [id] column remains dense:
-- create some test data
declare #t table (id int identity, name nvarchar(max))
insert #t ([name]) values ('item 1')
insert #t ([name]) values ('another item')
-- duplicate items, storing a mapping from src ID => dest ID
declare #mapping table (srcid int, [newid] int)
declare #Rows as Int = ( select Count(42) from #t )
insert #t ([name])
output inserted.id - #Rows, inserted.id into #mapping
select [name] from #t as source order by source.id -- Note 'order by' clause.
-- show results
select * from #t
select * from #mapping