Create custom defined unique identifier - sql

I have a table with uniqueidentifier column. Insert script looks like this :
INSERT INTO [Users] ([UserId], [Name], [Surname]) VALUES (NEWID(), 'SomeName', 'SomeSurname')
NEWID() creates new GUID, which is inserted to table. I would like to create some data with defined id column, not automatically generated. E.g. 'a0000000-0000-0000-0000-000000000000'. This code doesn't work because it throws error 'String or binary data would be truncated.' :
INSERT INTO [Users] ([UserId], [Name], [Surname]) VALUES ('a0000000-0000-0000-0000-000000000000', 'SomeName', 'SomeSurname')
I tried cast this custom guid, but I was not successful as well.
INSERT INTO [Users] ([UserId], [Name], [Surname]) VALUES (CAST('a0000000-0000-0000-0000-000000000000' AS uniqueidentifier), 'SomeName', 'SomeSurname')
Do you have any clue how I can solve inserting data with custom defined ID?

You don't have to cast it. SQL Server will do it for you.
This code works well:
create table x
( a uniqueidentifier
);
insert into x values ('A0000000-0000-0000-0000-000000000000')
;
insert into x values ('BBE46A77-3518-40E4-9B77-3275F3531B8B')
;
select *
from x
;

Related

While updating table1, how do I INSERT to table2 for every change in table 1?

I have a MEMBER table and NOTIFICATION table. On client side, I list all of the records in MEMBER table and there is a points column and this is shown as text input. So after I change the values for some members, I can click save button and this will update the records in my MEMBER table that's all right,
But the thing I want to accomplish is for every record whose points value has changed I want to INSERT a record in my notifications table.
I couldn't think of anything, how can I approach to this problem?
For notifications I made 3 tables by following the article in here
Use the output clause instead of trigger, they are bad.
You need the condition "where data_old <> data_new" case if you updated a column with the same value, SQL Server marked it as changed, even if the value hasn't changed
create table #example (id int identity(1,1) not null, data nvarchar(max));
insert into #example (data) values ('value 1'),('value 2'), ('value 3');
create table #audit (id int, data_old nvarchar(max), data_new nvarchar(max), [When] datetime not null default (getdate()));
insert into #audit (id, data_old, data_new)
select id, data_old, data_new
from (
update #example
set data = 'value changed'
output inserted.id, deleted.data as data_old, inserted.data as data_new
where id = 2
)changed (id, data_old, data_new)
where data_old <> data_new
select * from #audit
will result with this in #audit :
You have described what a trigger does.
create trigger trig_member_insert on members after update
as
begin
insert into notifications ( . . . )
select . . ., i.points as new_points u.points as old_points -- what you want to insert
from inserted i join
updated u
on i.member_id = u.member_id
where u.points <> i.points
end;
Storing something called "points" as a string seems like a very poor choice. It sounds like a number.

Insert data into the table from the finished procedure

How can I insert data into the table from the finished procedure, which was created using other scripts (data are on the rows in the results). This solutions was necessarily because I must concatenate coordinates.
One of the finishing step is:
select concat ('insert into table_shop ([IU], [ODD]) values ', data1)as PasteDat
from #tmp_07
In value data1 I have upload data.
When finished scripts I have result a lot of rows.
For example:
insert into table_shop ([IU], [ODD]) values ('A0001', 'D08')
insert into table_shop ([IU], [ODD]) values ('Agw44', 'D10')
insert into table_shop ([IU], [ODD]) values ('A5888', 'D18')
.
.
.
Now what I do is copying rows and paste on the other new query. Is there a more elegant way to do it in bulk?
Hope this helps
Use AdventureWorks2012
GO
Create Table #temp --table into which we need to insert
(
[DepartmentID] int,
[Name] varchar(50)
)
GO
Create PROCEDURE SP_ResultSet --SP which returns a result set
as
Select [DepartmentID]
,[Name]
from [HumanResources].[Department]
GO
Insert into #temp EXEC SP_ResultSet -- serves the purpose
GO
Select * from #temp order by [DepartmentID]

How to to get the value of an auto increment column in postgres from a .sql script file?

In postgres I have two tables like so
CREATE TABLE foo (
pkey SERIAL PRIMARY KEY,
name TEXT
);
CREATE TABLE bar (
pkey SERIAL PRIMARY KEY,
foo_fk INTEGER REFERENCES foo(pkey) NOT NULL,
other TEXT
);
What I want to do is to write a .sql script file that does the following
INSERT INTO foo(name) VALUES ('A') RETURNING pkey AS abc;
INSERT INTO bar(foo_fk,other) VALUES
(abc, 'other1'),
(abc, 'other2'),
(abc, 'other3');
which produces the error below in pgAdmin
Query result with 1 row discarded.
ERROR: column "abc" does not exist
LINE 3: (abc, 'other1'),
********** Error **********
ERROR: column "abc" does not exist
SQL state: 42703
Character: 122
Outside of a stored procedure how do a define a variable that I can use between statements? Is there some other syntax for being able to insert into bar with the pkey returned from the insert to foo.
You can combine the queries into one. Something like:
with foo_ins as (INSERT INTO foo(name)
VALUES ('A')
RETURNING pkey AS foo_id)
INSERT INTO bar(foo_fk,other)
SELECT foo_id, 'other1' FROM foo_ins
UNION ALL
SELECT foo_id, 'other2' FROM foo_ins
UNION ALL
SELECT foo_id, 'other3' FROM foo_ins;
Other option - use an anonymous PL/pgSQL block like:
DO $$
DECLARE foo_id INTEGER;
BEGIN
INSERT INTO foo(name)
VALUES ('A')
RETURNING pkey INTO foo_id;
INSERT INTO bar(foo_fk,other)
VALUES (foo_id, 'other1'),
(foo_id, 'other2'),
(foo_id, 'other3');
END$$;
You can use lastval() to ...
Return the value most recently returned by nextval in the current session.
This way you do not need to know the name of the seqence used.
INSERT INTO foo(name) VALUES ('A');
INSERT INTO bar(foo_fk,other) VALUES
(lastval(), 'other1')
, (lastval(), 'other2')
, (lastval(), 'other3')
;
This is safe because you control what you called last in your own session.
If you use a writable CTE as proposed by #Ihor, you can still use a short VALUES expression in the 2nd INSERT. Combine it with a CROSS JOIN (or append the CTE name after a comma (, ins) - same thing):
WITH ins AS (
INSERT INTO foo(name)
VALUES ('A')
RETURNING pkey
)
INSERT INTO bar(foo_fk, other)
SELECT ins.pkey, o.other
FROM (
VALUES
('other1'::text)
, ('other2')
, ('other3')
) o(other)
CROSS JOIN ins;
Another option is to use currval
INSERT INTO foo
(name)
VALUES
('A') ;
INSERT INTO bar
(foo_fk,other)
VALUES
(currval('foo_pkey_seq'), 'other1'),
(currval('foo_pkey_seq'), 'other2'),
(currval('foo_pkey_seq'), 'other3');
The automatically created sequence for serial columns is always named <table>_<column>_seq
Edit:
A more "robust" alternative is to use pg_get_serial_sequence as Igor pointed out.
INSERT INTO bar
(foo_fk,other)
VALUES
(currval(pg_get_serial_sequence('public.foo', 'pkey')), 'other1'),
(currval(pg_get_serial_sequence('public.foo', 'pkey')), 'other2'),
(currval(pg_get_serial_sequence('public.foo', 'pkey')), 'other3');

Inserting "bad" data into a SQL database?

I'm writing a query that inserts customer data into a MSSQL database. Very basic.
Unfortunately, I ran into a problem when trying to do the following:
INSERT INTO USERS(newid(),'BOB''S SELECT MARKETING')
I made sure to escape my quotes, but the server is still seeing SELECT as a reserved keyword. I don't want to have to wrap a bunch of reserved words in brackets. Is there a cleaner way of getting my data in the database intact and not mangled by brackets?
I appreciate your help.
Thank you!
You are missing the Key word VALUES:
INSERT INTO USERS VALUES (NEWID(),'BOB''S SELECT MARKETING');
You have several choices of syntax here. Using the one in your code sample, you forgot the VALUES keyword. For example:
declare #users table
(
id uniqueidentifier,
name varchar(50)
)
insert into #users values (newid(), 'BOB''S SELECT MARKETING')
You can also use the insert into / select statement like below if you are inserting a value into each one of the table's columns:
declare #users table
(
id uniqueidentifier,
name varchar(50)
)
insert into #users
select newid(), 'BOB''S SELECT MARKETING'
Or you can use the insert into / select statement and specify the columns you are inserting:
declare #users table
(
id uniqueidentifier,
name varchar(50)
)
insert into #users (id, name)
select newid(), 'BOB''S SELECT MARKETING'

Is there any way to retrieve inserted rows of a command

We probably all know SCOPE_IDENTITY() to retrieve the identity generated by a single insert. Currently I'm in the need of some kind of magic variable or function to retrieve all the rows generated by a statement, eg:
INSERT INTO [dbo].[myMagicTable]
(
[name]
)
SELECT [name]
FROM [dbo].[myMagicSource]
WHERE /* some weird where-clauses with several subselects ... */;
INSERT INTO [dbo].[myMagicBackupTable]
(
[id],
[name]
)
SELECT
[id],
[name]
FROM ???
An insert trigger is no option, as this will perform a single insert which is a problem for a batch of 10.000 rows...
So, is there any way to achieve this?
We are using mssql2005<
For SQL Server 2005+, you can use the OUTPUT clause.
DECLARE #InsertedIDs table(ID int);
INSERT INTO [dbo].[myMagicTable]
OUTPUT INSERTED.ID
INTO #InsertedIDs
SELECT ...
You could define a temporary table (possibly a table variable) and make use of the OUTPUT clause on your INSERT (you can make use of the Inserted pseudo-table, like in a trigger):
DECLARE #NewIDs TABLE (MagicID INT, Name VARCHAR(50))
INSERT INTO [dbo].[myMagicTable]([name])
OUTPUT Inserted.MagicID, Inserted.Name INTO #NewIDs(MagicID, Name)
SELECT [name]
FROM [dbo].[myMagicSource]
WHERE /
and then use that table variable after the INSERT:
INSERT INTO
[dbo].[myMagicBackupTable]([id], [name])
SELECT MagicID, [name]
FROM #NewIDs
and go from there.