Selecting from one table and modifying it before importing - sql

I have since modified this process and hopefully simplified. In the past, I had two tables, tablename and result. Tablename had a column (56th of 90) named cnty which was char(3). The second table, result, had a field which essentially was 000 + cnty. This field is titled area. I was trying to insert the cnty values from tablename, add the three zeros at the beginning and place them in the result table under the column, area.
Now I have both columns in result. Area is blank for now. Cnty contains the values that were in tablename (79954 of them).
Sample data
area employment busdesc cnty
410 gas station 003
Desired Result
area employment busdesc cnty
000003 410 gas station 003

Try the following query:
update dbo.result
set area = concat('000',cnty);
Hope it helps!

update res
set res.area = '000' + tbl.cnty
from Result res inner join [originalTable] tbl
on res.id=tbl.id --Don't know how to join both tables, let us know
EDIT: In regard to the last comment, let's create a new table Results2 (because I don't know all the columns in the table) This table will have all columns of tablename plus new Area column.
select *, '000' + cnty as AREA
into Results2
from dbo.tablename;
You have to specify each column or in this case an asterisk * will do

Is this the syntax you are looking for?
insert into dbo.result (name1, area)
select name1, '000' + cnty
from dbo.tablename;
Or, if the table doesn't already exist:
select name1, ('000' + cnty) as area
into dbo.result
from dbo.tablename;

Related

Combine Multiple Rows Into A Single Column

I am working on a stored procedure for reporting purposes and I need to combine rows in a single column but I can't find a way to do this. I have four tables, Case, Debtor, DebtorAddress and CaseNote. Rather than try to do this in a single statement I decided to create a temp table with the columns needed, populate the ones that occupy a single row, then use an update statement to combine the multiple rows of the last column needed into a single row. My temp table has rows for CApKey (the ID of the Case table), OwnerName (from Debtor), Address (from DebtorAddress, and Note. For each Case there may be multiple Notes (stored in the CaseNote table). So I may have Case #1, with a CApKey value of 1, OwerName of John Jones, Address of 1234 Main St. There may be one Note the says 'Called and left message', another that says 'Sent letter', and another that says 'Left a second voicemail', etc. I'd like to combine the three notes into a single row with Note values of Called and left a message, Sent Letter, and Left a second voicemail. I can use space, period, or comma as a delimiter. I found a way to do the update in theory but I'm getting an error that the sub-query returned more than 1 value. Below is the "heart" of the procedure. I've been wracking my brain on this for two days now. Any assistance is greatly appreciated in advance. Here is the statement I'm trying:
CREATE TABLE #temp
(
CaseKey int,
OwnerName varchar(500),
Address varchar(500),
Note varchar(MAX)
)
DECLARE #val Varchar(MAX);
INSERT INTO #temp
(CaseKey, OwnerName, Address)
SELECT ca.CApKey, DEFirstName + ' ' + DELastName, da.DAAddress1
FROM [Case] ca INNER JOIN Debtor de ON ca.CApKey = de.CApKey INNER JOIN DebtorAddress da ON ca.CApKey = da.CApKey
WHERE ca.LFpKey = #LFpKey AND de.DEIsPrimary = 1
UPDATE #temp SET Note =
(SELECT COALESCE(#val + ', ' + CANNote, CANNote)
FROM CaseNote WHERE CApKey = 51)
--SELECT #val;)
SELECT * FROM #temp
Thanks!
If i understood you correctly, you need to combine all the notes.
Get your data, queried from the 4 tables into a table (ex. #t)
Then you can use XML PATH and Stuff to achieve your goal (later you can use that for whatever your purpose as inserting to a table or display in a report etc)
SELECT CaseKey, OwnerName, Address, (STUFF((
SELECT ', ' + Note
FROM #t tx
where tx.CaseKey = t.CaseKey and tx.OwnerName = t.OwnerName and tx.Address = t.Address
FOR XML PATH('')
), 1, 2, '')
) AS StringValue
From #t t
Group by CaseKey, OwnerName, Address
Here is the fiddle

How to insert a specific text at the end of exisitng data in a specific column?

I am using SQL Server 2014. Assume I have a table called T1 with 2 columns, IdNumber and Notes. Table T1 contains around 300,000 records.
The Notes column is a free text column, meaning users have entered therein free text. Some records have this column empty (no text entered).
I now have a list of IdNumbers where I need to add this specific text "(TOC)" in the Notes column of T1, ideally at the end of any text already present therein. I have created a table called tempID which contains the list of all these IdNumbers.
Here is how table T1 looks (extract):
IdNumber Notes
--------------------------------------------------------------------
101 Guest does not like beer
154 wedding anniversary - to prepare a cake - 03052020
160
IdNumber = 160 has a blank/empty Notes column.
Here is what I want to achieve (assuming "(TOC)" need to be added to these 3 IdNumbers):
IdNumber Notes
------------------------------------------------------------------------
101 Guest does not like beer (TOC)
154 wedding anniversary - to prepare a cake - 03052020 (TOC)
160 (TOC)
How can I do this (I have a list of around 1500 IdNumbers)?
This is where I am stuck with my SQL query:
UPDATE T1
INSERT INTO [Notes]
VALUE ('(TOC)') ----stuck here!
WHERE [IdNumber] in (Select [IdNumber] from [tempID]
I think it should be done differently since my above query will simply overwrite the existing content of the Notes column with "(TOC)".
Actually, concat() does exactly what you want -- ignoring NULL values:
UPDATE dbo.T1
SET Notes = CONCAT(Notes, ' (TOC)')
WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);
The only caveat is that you seem to want ltrim() to remove the leading space when notes is NULL:
UPDATE dbo.T1
SET Notes = LTRIM(CONCAT(Notes, ' (TOC)'))
WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);
This will remove the leading space for NULL values -- and any leading NULLs in notes.
You can do this with COALESCE() and + as well:
UPDATE dbo.T1
SET Notes = COALESCE(Notes + ' ', '') + '(TOC)'
WHERE IdNumber IN (SELECT t.IdNumber FROM dbo.tempID t);
try this:
UPDATE T1
SET T1.Notes = ISNULL(T1.Notes + ' ', '') + '(TOC)'
from T1 inner join dbo.tempID T2 on T1.IdNumber=T2.IdNumber
You need to just simply add (TOC) to your column - and make sure to be aware that if Notes is NULL, you need to do some extra handling:
UPDATE dbo.T1
SET Notes = ISNUL(Notes, '') + ' (TOC)'
WHERE IdNumber IN (SELECT IdNumber FROM dbo.tempID);
With the ISNULL() operator, you turn a NULL into an empty string, which can then be concatenated with the (TOC) string. If you omit this, then it wouldn't work, because concatenating NULL with anything else will still results in NULL

SQL combine 2 rows into 1 row then delete 1

I'm trying to complete an SQL query homework question and cannot figure out how to add 2 rows together from the same table, with the intention of deleting one after they are combined.
I have a table name 'country', in it, I have 241 rows of data with columns.
name region area population GDP
------------------------------------------------------------------------
Hong Kong Southeast Asia 1040 5542869 136100000000
China Asia 9596960 1203097268 2978800000000
Expected output:
name region area population GDP
-------------------------------------------------------------------
Hong Kong Southeast Asia 1040 5542869 136100000000
China Asia 9598000 1208640137 3114900000000
The goal is to keep the name of the row as "China" and the region as "Asia" but adding the numeric values from the "Hong Kong" row to the "China" row for the columns (area, population, and GDP).
I have tried UNION and MERGE but I'm not familiar with using them and couldn't get it to work.
I feel like it has to be something like the SQL query below:
update country
set area = area.HongKong + area.China
where name = 'China';
but I don't know the proper way to reference a specific row.
Ah yes, homework. I remember those days.
Here is some code to help out -
--create a temp table to hold sample data
select
*
into #country
from
(
values
('Hong Kong', 'Southeast Asia', 1040, 5542869, 136100000000),
('China', 'Asia', 9596960, 1203097268, 2978800000000),
('USA', 'North America', 1, 10, 100) --some other row in table
) d ([name], region, area, population, gdp);
select * from #country;
Here is what the data looks like in this table:
--update statement
with
Totals as
(
select
count(1) rows, --should be 2
sum(area) areaTotal,
sum(population) populationTotal,
sum(gdp) gdpTotal
from #country
where [name] in ('Hong Kong', 'China') --this filter may be insufficient; it would be better to select by a primary key such as a rowID but the table does not have one
)
update c
set c.area = t.areaTotal,
c.population = t.populationTotal,
c.gdp = t.gdpTotal
from #country c
inner join totals t
on c.[name] = 'China';
Here is what the data looks like after the update:
There are a few noteworthy things here:
The code above the update statement, with Totals as (..., is called a common table expression (also abbreviated as CTE). It is being used here to contain the query that calculates the totals needed to perform the update. A CTE is one approach to creating an intermediate data set. Alternative approaches to this include: creating a temp table or using a derived table.
To see the results of the query within the CTE, those lines of code can be highlighted in your editor and executed against the database.
The original post said there are 241 rows of data in the country table. This means it is important to have a reliable filter in the query that calculates the totals so the correct rows for summing are isolated. The preferred way to filter the rows is to use a primary key, such as a rowID. Since this table does not have a primary key column, I made a guess and used the [name] column.
The purpose of count(1) rows in the CTE is to make sure only 2 rows are being summed. If this number comes back as anything other than 2, it means there is a problem with the filter and the where clause needs to be modified. The number of rows will only be visible when you do #2 above.
Now the Hong Kong row needs to be cleaned up:
--delete old row
delete from #country where [name] = 'Hong Kong';
This is what the data looks like now:
Again, it would be preferable to use a primary key column in the where clause instead of the [name] column to be certain that the correct row is being deleted.

show a record in datagridview that is not in the table

how to show the record in datagridview when it is not in database and get the date of that record.
for example
in my database i have a record like this
as you can see john dont have a record in 2/15/2016 and ken dont have a record in 2/16/2016
now in data gridview it should be show like this
is it posible to get this record? i dont have an idea to do these im realy need help. Im using vb and ms-access as database.
Does something like this work in Access?
select *, 'absent'
from (
select *
from (select distinct empname from table) n, (select distinct empdate from table) d
) sq
where sq.n + '-' + sq.d not in (select empname + '-' + empdate from table)
I might not have that just right, but the point is, if you get a cartesian table of all names and dates and then eliminate the ones that appear in your DB, the ones that remain are the absences.

Pad 0's to returned query and insert into temp table

Got sql to pad 0's from: Formatting Numbers by padding with leading zeros in SQL Server
What I want to do is get a users order history from our Navigator database tables. We have a process that puts the orders from the website tables into the the navigator tables (because the orders need to be formatted for the nav table).
I want to query the website tables to get the orders from a logged in user using their user id:
SELECT OrderID FROM db1.zm.dbo.zOrder WHERE AccountID = 631180 (this returns multiple order id's)
db1 is the server, zm is database.
The OrderID's returned are formatted like 4565, 5675, ect. I want to insert them into a temp table like: Z0004565 with a Z and enough leading 0's to hit 7 digits for the number.
How do I modifiy the select statement to do so? Or can I.
SQL for padded 0's: SELECT REPLICATE('0', 7-LEN(4665)) + 4665
SQL Following Comments:
DECLARE #OrderNumTable table (orderNum varchar(20))
INSERT INTO #OrderNumTable EXEC( SELECT (''Z'' + REPLICATE(''0'', 7-len(OrderID)) + OrderID)FROM db1.zm.dbo.zOrder WHERE AccountID = 631180
SELECT OrderID,
'Z'+RIGHT('0000000'+CAST(OrderID AS VARCHAR(7)),7)
FROM db1.zm.dbo.zOrder
WHERE AccountID = 631180
Updated following the question edit
DECLARE #OrderNumTable table (orderNum varchar(8))
INSERT INTO #OrderNumTable(orderNum)
SELECT 'Z'+RIGHT('0000000'+CAST(OrderID AS VARCHAR(7)),7)
FROM db1.zm.dbo.zOrder
WHERE AccountID = 631180
Can you not just add a Z to the front?
SELECT 'Z' + REPLICATE('0', 7-LEN(OrderID)) + LTRIM(STR(OrderID))