Combining multiple queries & returns - sql-server

I have a .csv file with a list of 100 product_ids. I have a SQL Server table which (amongst others) has a product_id column (4000+ ids) and a product_description column.
What I want to do is take the .CSV list of product_ids and run a query on the table to return a list of the relevant product_description.
So my simple query would be
select product_description
from tablename
where product-id = xxxxxxx.
But how do I supply the xxxxxx as a list (perhaps I just seperate with commas?) and dump the output into another csv.

Can't you just copy + paste the id's from the CSV into a query?
SELECT
product_id
, product_description
FROM <table>
WHERE product_id in (<<list of values from CSV>>).
Since they're already in a CSV, they should be comma delimited, so you can easily plug them into your query (if you open your file with a text editor).
Alternatively, you could do everything from SQL, like this:
CREATE TABLE #TempTable (
ID integer
, col2 ..
, col3 ..
etc. )
GO
BULK INSERT #TempTable
FROM 'C:\..\file.csv'
WITH
(
FIRSTROW = 2, -- in case the first row contains headers (otherwise just remove this line)
FIELDTERMINATOR = ',', -- default CSV field delimiter
ROWTERMINATOR = '\n',
ERRORFILE = 'C:\CSVDATA\SchoolsErrorRows.csv',
TABLOCK
)
And then just run:
SELECT
product_id
, product_description
FROM <table>
WHERE product_id in (SELECT ID FROM #TempTable)
If you want to export this result to another CSV then:
INSERT INTO OPENROWSET(
'Microsoft.ACE.OLEDB.12.0'
,'Text;Database=D:\;HDR=YES;FMT=Delimited'
,'SELECT
product_id
, product_description
FROM <table>
WHERE product_id in (SELECT ID FROM #TempTable)' )

Related

How can we insert the column name from one table into a another table as row using java script

create table test(columnname varchar(100))
CREATE or replace TABLE brand(
Brand VARCHAR(150),
Day DATE,
Users VARCHAR(150)
);
SELECT array_agg(column_name)
FROM information_schema.columns
where table_name = 'brand';
using this query i am getting a single line, but to insert it as row
excepted output:
select * from test
columnname
Brand
Day
Users
If you want many values from you ‘test’ table when you select from the information schema don't use array_agg to turn the many rows into a single line.
To insert:
insert into test
SELECT column_name
FROM information_schema.columns
where table_name = 'brand';

Parse XML and generate new rows through SQL Query

I've the input data in SQL table in below format:
ID Text
1 <Key><Name>Adobe</Name><Display>Ado</Display></Key><Key>.....</Key>
2 <Key><Name></Name><Display>Microsoft</Display><Version>1.1</Version></Key>
There can be multiple keys for each ID.There could be several thousand rows in a table in above format. I've to generate the final sql output in below format
ID Name Display Version
1 Adobe Ado
1 xyz yz 1.2
2 Microsoft 1.1
I am using the below query to parse Text column, but getting all data in one row. How can I split that data in multiple rows as indicated above.
SELECT
CAST(CAST(Text AS XML).query('data(/Key/Name)') AS VARCHAR(MAX)) AS Name,
CAST(CAST(Text AS XML).query('data(/Key/Display)') as VARCHAR(MAX)) AS DisplayName,
CAST(CAST(Text AS XML).query('data(/Key/Version)') AS VARCHAR(MAX)) AS Version
FROM
ABC where ID = 1
Currently I am running this query for each ID at a time. Is there a way to run for all ID's together. Also, is there any other efficient way to get the desired output.
Here is the example:
-- Sample demonstrational schema
declare #t table (
Id int primary key,
TextData nvarchar(max) not null
);
insert into #t
values
(1, N'<Key><Name>Adobe</Name><Display>Ado</Display></Key><Key><Name>xyz</Name><Display>yz</Display><Version>1.2</Version></Key>'),
(2, N'<Key><Name></Name><Display>Microsoft</Display><Version>1.1</Version></Key>');
-- The actual query
with cte as (
select t.Id, cast(t.TextData as xml) as [XMLData]
from #t t
)
select c.Id,
k.c.value('./Name[1]', 'varchar(max)') as [Name],
k.c.value('./Display[1]', 'varchar(max)') as [DisplayName],
k.c.value('./Version[1]', 'varchar(max)') as [Version]
from cte c
cross apply c.XMLData.nodes('/Key') k(c);
Different type can be corrected with the in-place cast/convert done in CTE (or equivalent subquery).

Error inserting comma separated values in Table: SQL Server 2008

I have two tables called 'ticket' and 'ticket_category'.
'Ticket' table has a column 'Ticket_Uid' and its type is 'UniqueIdentifier'.
Each 'ticket_uid' in 'ticket' table has one-to-many mappings in 'ticket_category' table.
E.g.
'Ticket' table:
Ticket_Uid
100
Ticket_Category:
Ticket_Uid Ticket_Category_Uid
100 ABC
100 DEF
100 XYZ
I want to create the following table named 'comment_mining':
Ticket_Uid Category_List
100 ABC,DEF,XYZ
The table has already been created using the following:
create table dbo.comment_mining
(
Ticket_UID [uniqueidentifier] NOT NULL,
time_created datetime,
time_closed datetime,
total_time_taken int,
category_list nvarchar(500),
comment_list varchar(8000)
);
I have already created this table and populated the 'Ticket_Uid' column.
For inserting into the 'category_list' column, I am using the following query:
insert into dbo.comment_mining(category_list)
SELECT
(SELECT distinct convert(varchar(500),category_id) + ',' AS [text()]
FROM ticket_category pr
WHERE pr.ticket_uid = p.ticket_uid
FOR XML PATH (''))
AS Category_list
FROM comment_mining p
When I run the above query, it gives me the following error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Ticket_UID', table 'Support_Saas.dbo.comment_mining'; column does not allow nulls. INSERT fails.
The statement has been terminated.
(which is strange as I am not even inserting in the 'Ticket_Uid' column)
When I run the same query without the insert statement, it executes perfectly. The query is as follows:
SELECT
(SELECT distinct convert(varchar(500),category_id) + ',' AS [text()]
FROM ticket_category pr
WHERE pr.ticket_uid = p.ticket_uid
FOR XML PATH (''))
AS Category_list
FROM comment_mining p
Yes there are some NULL values when the above query is run, but 'category_list' column in 'comment_mining' table can take NULL values. Why is the error on 'ticket_Uid' column?
Would someone please be able to explain why this is happening and what's the cure to this?
P.S. - I am new to SQL.
The reason you have the insert error on table comment_mining is because you set the Ticket_Uid column as not null; however, since it does not have a default value, the insert fails because whether you're inserting that field specifically or not, when a row is created, all columns must be filled in or be null.
You can do one of 2 things:
Change the structure of the comment_mining table to have a default value for Ticket_Uid (You can do this in the table designer or with code:
Example 1:
Alter Table comment_mining
Add Constraint DF_CommentMining_1 default NewID() for Ticket_UID
Make your insert explicitly include a generated uniqueidentifier (GUID) value by using the SQL NewID() function to populate the Ticket_UID UniqueIdentifier column
Example 2:
insert into dbo.comment_mining(Ticket_Uid, category_list)
SELECT NewID(),
[ your subquery ]...
In both cases, you're now satisfying the NOT NULL constraint on comment_mining.Ticket_UID, either by making it automatically populate itself, or by supplying a value.
try this,
;with cte as
(
select 100 Ticket_Uid,'ABC' Ticket_Category_Uid union all
select 100 , 'DEF' union all
select 100, 'XYZ'
)
select distinct b.Ticket_Uid,
stuff((select ','+a.Ticket_Category_Uid from cte a where a.Ticket_Uid=b.Ticket_Uid for xml path('')),1,1,'')
from cte b

Insert records into table in SQL server

Is there a way in SQL SERVER(05 & 08) that I can insert records from an external file into a temp table? I do not have privilege to the database at all. Here is what i tried to do:
CREATE table #temp
(KEY_ID INT)
INSERT INTO #temp
SELECT 90883000
Ran #temp table with result:
KEY_ID
---------
90883000
It kind of works with just one record. How do I do if I have hundred records? Thanks a lot!!!
This just to show how to add multiple rows in a table.
CREATE table #temp(
KEY_ID integer
)
Declare #i as int
set #i = 1
WHILE (#i <= 10000)
BEGIN
insert into #temp values(#i)
set #i += 1
End
How about a table variable. I believe that the #temp need rights to the tempdb database. I believe that a table variable is used just like any other variable which is session based.
To declare a table variable:
DECLARE #ProductTotals TABLE
(
ProductID int,
Revenue money
)
Insert into a table variable:
INSERT INTO #ProductTotals (ProductID, Revenue)
SELECT ProductID, SUM(UnitPrice * Quantity)
FROM [Order Details]
GROUP BY ProductID
For importing files, you can use BULK IMPORT. Use this to get the data into your temp table, then you can run set based operations against it.
A more effective way of inserting a lot of rows.
INSERT INTO #temp
(KeyID)
SELECT TOP 1000 -- PUT YOUR QUANTITY HERE
IDENTITY(INT,1,1) AS N
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
If you're going to be using this a lot, just ask them to create you a TALLY TABLE.
This is how I usually do it if I have the values in a file somewhere. Inserting hundreds of records from flat text file into temp table. My example only has one column, but as long as the flat file is delimited somehow, you can do as many columns as needed. Need to make sure you put the text file in a directory you have access to.
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable
CREATE TABLE #TempTable(Col1 varchar(10)) --Specify temp-table name & columns
BULK INSERT #TempTable
FROM 'C:\FileName.txt' --Specify file path/name
WITH (
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
);
GO

SQL Server table to xml

this time i have question how to convert MSSQL table to XML
My source SQL table:
+-----------+-----------------+
|atributname|atributvalue |
+-----------+-----------------+
|phone |222 |
|param4 |bbbbcdsfceecc |
|param3 |bbbbcdsfceecc |
|param2 |bbbbcdsfccc |
+-----------+-----------------+
Expected result sample:
<items>
<phone>222</phone>
<prama4>bbbbcdsfceecc</param4>
<param3>bbbbcdsfceecc</param3>
<param2>bbbbcdsfccc</param2>
</items>
I tried lot of variations of the following query
SELECT atributname,atributvalue
FROM sampletable FOR XML PATH (''), ROOT ('items');
but results are not good :( should be exactly like in "Expected result sample"
any help
ps
Script to create sampletable:
create table sampletable
(atributname varchar(20),
atributvalue varchar(20))
insert into sampletable (atributname,atributvalue)
values ('phone','222');
insert into sampletable (atributname,atributvalue)
values ('param4','bbbbcdsfceecc');
insert into sampletable (atributname,atributvalue)
values ('param3','bbbbcdsfceecc');
insert into sampletable (atributname,atributvalue)
values ('param2','bbbbcdsfccc');
That's not how FOR XML works. It's columns that get turned into XML elements, not rows. In order to obtain the expected result, you would need to have columns named phone, param4, and so on - not rows with these values in attributename.
If there are specific elements you want in the XML, you could perform a pivot on the data first, then use FOR XML.
Example of a pivot would be:
SELECT [phone], [param2], [param3], [param4]
FROM
(
SELECT attributename, attributevalue
FROM attributes
) a
PIVOT
(
MAX(attributevalue)
FOR attributename IN ([phone], [param2], [param3], [param4])
) AS pvt
FOR XML ROOT('items')
Of course the aggregate will only work if attributevalue is a numeric data type. If it's a character-type column, then you'll have some trouble with the pivot, as there are no built-in string aggregates in SQL server AFAIK...
ok
finally i have done this in several ways,
but this is simplest version suitable for medium dataset
declare #item nvarchar(max)
set #item= (SELECT '<' + atributname +'>' +
cast(atributvalue as nvarchar(max)) +'</' + atributname +'>'
FROM sampletable FOR XML PATH (''), ROOT ('items'));
select replace(replace(#item,'<','<'),'>','>')

Resources