Following Situation:
I have a dynamically (by columns) builded table ... eg:
Rowid UniqueID Name Birthdate Town ....
1 null Joe Jan-93 Cologne
2 null Nick Okt-00 London
I am building this TempTable to create an uniqueID for all Data in my DataBase
The TempTable was created by two loops which run through all my DataBase Table & Columns and copy all primary key Data to this TempTable.
My aim is to update the UniqueID Column from my TempTable with the concat values of data ... eg:
UniqueID
JoeJan-93Cologne
NickOkt-00London
Do you have an idea how to update UniqueID ?
What I m thinking about is:
Loop 1 going through all Tables
Select Table of Schema
Loop 2 going through all Columns of Table
Select Column of Schema
Copy Column to my Temp
-- here an update like ... set UniqueID = select concat(UniqueID, #Column)
-- from #table where RowID = RowID
End loop 2
end loop 1
Is this possible
Or do I have to open a third loop which is running through all rows and concat values ?
You can try this
Update <YourTableName>
set UniqueId = ISNULL(Name, '') + ISNULL(Cast(Birthdate as Varchar(10), '') + ISNULL(Town, '')
You can use CONCAT() with UPDATE statement, no any loop required :
UPDATE t
SET UniqueID = CONCAT(Name, Birthdate, Town);
Related
I am trying to capture if my SQL Query have 0 rows or multiple rows. If it has 0 rows then I will insert, if 1 will perform an update, if > 1 will perform additional analysis.
Is there a way I can see if my query resulted in x results or no results in automation anywhere?
Any assistance will be appreciated.
You can make use of if exists and if not exists and check if rows exists or not, or even if there are multiple before doing the insert.
Here is a simple example using if not exists where if the row doesn't exist on dbo.Table it will insert a row. If it already exists then the ID will be logged to an Error table.
declare #InsertID int = 5, #Name nvarchar(max) = 'some name'
if ((select count(1) from dbo.Table where ID = #InsertID) > 1) -- detect error; more than one record for an id
begin
insert into dbo.Error (ErrorID, ErrorDate)
select #InsertID, getdate()
end
else if not exists (select 1 from dbo.Table where ID = #InsertID) -- no record exists for ID, insert it
begin
insert into dbo.Table (ID, Name)
select #InsertID, #Name
else if exists (select 1 from dbo.Table where ID = #InsertID) -- update the single record
begin
update dbo.Table set Name = #Name where ID = #InsertID
end
A2019 returns the results of a SQL Query as a table...
You could have an if statement right after your query which checks to see if the row count of the returned table is > 0 then take action accordingly.
I'd like to use a return from a procedure in a CASE statement. It can't be a function because that procedure returns an inserted key.
UPDATE TIM
SET CD_LINHA_EVENTO =
CASE WHEN
TIM.CD_SUBESTRUTURA_PARAMETRO = (SELECT TOP 1 SPZ.CD_SUBESTRUTURA_PARAMETRO FROM SUBESTRUTURA_PARAMETRO SPZ WITH (NOLOCK) WHERE SPZ.CD_SUBESTRUTURA = TIM.CD_SUBESTRUTURA
AND SPZ.FL_SELECAO = 1 ORDER BY SPZ.NR_ORDEM)
THEN
**EXEC [dbo].[SPRTO_NumeracaoEventos]**
ELSE
(SELECT MAX(TIM2.CD_LINHA_EVENTO) FROM #TB_INSERTED_MODIFIED TIM2 WITH(NOLOCK))
END
FROM #TB_INSERTED_MODIFIED TIM WITH (NOLOCK)
stored procedure [SPRTO_NumeracaoEventos]:
INSERT INTO TB_NUMERACAO_EVENTOS (VALOR) VALUES ('')
RETURN SCOPE_IDENTITY()
Thank you!
I wasn't able to figure out your table schema well enough to provide a direct answer, but I put together a way to use inserted identity values within an update trigger. Hopefully you can adapt this to fit your specific use case.
Have a look at this SQL Fiddle
As noted in the comments in the fiddle, this strategy is based on using the OUTPUT clause to capture identity values into a table variable. See http://msdn.microsoft.com/en-us/library/ms177564.aspx for more on the OUTPUT clause.
For rows where the case is true, we insert one row per true case into the secondary table and capture the identities to a table variable, then we update the underlying table with a row number join between the inserted virtual table and the identity table variable. Then we run another update for the rows where the case is false. Here's the relevant trigger code from my fiddle example.
-- Create a table variable to hold identity ID values from OUTPUT clause
DECLARE #table_2_ids TABLE (id INT NOT NULL)
-- Insert to our secondary table where the condition is true and capture the identity values to table variable
INSERT table_2 (textval)
OUTPUT inserted.id INTO #table_2_ids
SELECT 'from trigger'
FROM inserted
WHERE flag = 1
-- Use row number to match up rows from inserted where the condition is true to the identity value table variable
-- Update matched identity id to underlying table
UPDATE t
SET table_2_id = r.id, textval = textval + ' and trigger inserted to table_2'
FROM table_1 t
JOIN (SELECT id, ROW_NUMBER() OVER (ORDER BY id) rn FROM inserted WHERE flag = 1) i ON i.id = t.id
JOIN (SELECT id, ROW_NUMBER() OVER (ORDER BY id) rn FROM #table_2_ids) r ON r.rn = i.rn
-- and now update where condition is false
UPDATE t
SET textval = textval + ' and trigger did not insert to table_2'
FROM table_1 t
WHERE flag = 0
My Table Schema is as follows:
Gender: char(1), not null
Last Name: varchar(25), null
First Name: varhcar(35), not null
The data in the table looks like:
Gender | Last Name | First Name |
M Doe John
F Marie Jane
M Jones Jameson
F Simpson Alice
I now am trying to update all the names in the table from the names present in the txt file.
My Query is as follows:
-- Sort out the Forenames we'll be using for the data, we make a #Name2 table because I have yet to figure our
-- inserting specific columns using BULK INSERT and without using a format file.
CREATE TABLE #Name (Name VARCHAR(50))
CREATE TABLE #ForeNames (FirstName VARCHAR(50), Gender VARCHAR(1))
-- Move data in the #Name2 table
BULK INSERT #Name FROM "c:\girlsforenames.txt" WITH (ROWTERMINATOR='\n')
-- Now move it to the forename table and add the gender
INSERT INTO #ForeNames SELECT [Name], 'F' FROM #Name
-- Delete the names from temporary table
TRUNCATE TABLE #Name
-- Same for the boys
BULK INSERT #Name FROM "c:\boysforenames.txt" WITH (ROWTERMINATOR='\n')
INSERT INTO #ForeNames SELECT [Name], 'M' FROM #Name
-- Now do the surnames
TRUNCATE TABLE #Name
BULK INSERT #Name FROM "c:\surnames.txt" WITH (ROWTERMINATOR='\n')
DECLARE #Counter BIGINT
SET #Counter = 4
WHILE (#Counter > 0)
BEGIN
UPDATE TableName
set
[last_name]= (SELECT TOP 1 FirstName from #ForeNames),
[first_name]=(SELECT TOP 1 Name FROM #Name ORDER BY NEWID()),
[gender]= ( SELECT TOP 1 Gender FROM #ForeNames ORDER BY NEWID());
SET #Counter=#Counter-1
END
DROP TABLE #Name
DROP TABLE #ForeNames
SELECT * FROM TableName
What Happens is all the rows in the table are updated with the same values and each time i execute the query they are updated with the new set of values.
What I want is to loop through each row and update it and den update the next row with the other set of random name. But here it is updating the same random name across all the rows of the table.
Any help would be appreciated.
Each SELECT statement is only being executed once in your example (and thus returning 1 result), and since your UPDATE isn't being limited, you're applying the same value to every row.
If you want to update each row with different values, you can use a CTE and the ROW_NUMBER() function to update rows at a time.
There's no need to loop, you can do it in one fell swoop:
WITH cte AS (SELECT *,ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS n1
FROM TableName
)
UPDATE cte
SET FirstName = names.Name
FROM cte
JOIN (SELECT *,ROW_NUMBER() OVER (ORDER BY NEWID()) AS n2
FROM #name
)names
on cte.n1 = names.n2
Demo: SQL Fiddle
This example is just for the FirstName.
My SQL table have a column name AddressName . I am storing customer address name in that column. And I want to store them in the following format, suppose when I inserted first time a value in that column it stored 'Utpal' in that field next time before inserting any value I want to fetch the next string value to be inserted as 'Utpal2' and will insert that value in the table.Similarly in the next insertion the value should be 'Utpal3'.How to do this task using SQL query please help.
Thanks and Regards
Utpal Maity
Something like this would help you. Just an example:
TABLE SCHEMA:
create table person
(
id int identity(1,1),
address varchar(50)
)
GO
SCRIPT: (partial)
--insert second record
insert into person
select top 1 left(address, case patindex('%[0-9]%', address) when 0 then len(address) else patindex('%[0-9]%', address) - 1 end) +
convert(varchar(10),convert(numeric(10,0),Coalesce(NULLIF(right(address, case patindex('%[0-9]%', address)
when 0 then 0
else len(address) - patindex('%[0-9]%', address) + 1
end
)
,'')
,0)
) + 1
)from person
order by id desc
GO
Check out SqlFiddle:
I'm working on a database which has the following table:
id location
1 Singapore
2 Vancouver
3 Egypt
4 Tibet
5 Crete
6 Monaco
My question is, how can I produce a query from this which would result in column names like the following without writing them into the query:
Query result:
Singapore , Vancouver, Egypt, Tibet, ...
< values >
how can I produce a query which would result in column names like the
following without writing them into the query:
Even with crosstab() (from the tablefunc extension), you have to spell out the column names.
Except, if you create a dedicated C function for your query. The tablefunc extension provides a framework for this, output columns (the list of countries) have to be stable, though. I wrote up a "tutorial" for a similar case a few days ago:
PostgreSQL row to columns
The alternative is to use CASE statements like this:
SELECT sum(CASE WHEN t.id = 1 THEN o.ct END) AS "Singapore"
, sum(CASE WHEN t.id = 2 THEN o.ct END) AS "Vancouver"
, sum(CASE WHEN t.id = 3 THEN o.ct END) AS "Egypt"
-- more?
FROM tbl t
JOIN (
SELECT id, count(*) AS ct
FROM other_tbl
GROUP BY id
) o USING (id);
ELSE NULL is optional in a CASE expression. The manual:
If the ELSE clause is omitted and no condition is true, the result is null.
Basics for both techniques:
PostgreSQL Crosstab Query
You could do this with some really messing dynamic sql but I wouldn't recommend it.
However you could produce something like below, let me know if that stucture is acceptable and I will post some sql.
Location | Count
---------+------
Singapore| 1
Vancouver| 0
Egypt | 2
Tibet | 1
Crete | 3
Monaco | 0
Script for SelectTopNRows command from SSMS
drop table #yourtable;
create table #yourtable(id int, location varchar(25));
insert into #yourtable values
('1','Singapore'),
('2','Vancouver'),
('3','Egypt'),
('4','Tibet'),
('5','Crete'),
('6','Monaco');
drop table #temp;
create table #temp( col1 int );
Declare #Script as Varchar(8000);
Declare #Script_prepare as Varchar(8000);
Set #Script_prepare = 'Alter table #temp Add [?] varchar(100);'
Set #Script = ''
Select
#Script = #Script + Replace(#Script_prepare, '?', [location])
From
#yourtable
Where
[id] is not null
Exec (#Script);
ALTER TABLE #temp DROP COLUMN col1 ;
select * from #temp;