How to insert records using a SELECT statement? - vb.net

Background
I currently have a table named Parts_list that is structured as shown below:
_id is autoincrementing so I always provide NULL which works fine.
I would like to use a SELECT statement to populate this table but have difficulties how to write the INSERT SELECT statement.
What I have tried
For testing I have tried this SQL statement:
INSERT INTO Parts_list VALUES
(null, 'My Name',CURRENT_TIMESTAMP, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null,
null, null, null,null, null, null)
and it inserts a new line without any problem.
Problem
However when I try something like this:
INSERT INTO Parts_list VALUES
(null, 'My Name',CURRENT_TIMESTAMP, Part_ID, null, null, null,
null, null, null,null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null,
null, null)
SELECT Part_ID FROM tracking_vehicles
where I am selecting one column and trying to insert this column, nothing happens. Do I have something wrong with my syntax? In my example "Part_ID" is VARCHAR, which matches the data type that it is being inserted to. Any help or guidance is appreciated.
PS I also tried this:
INSERT INTO Parts_list
(null, 'My Name',CURRENT_TIMESTAMP, Part_ID, null,
null, null, null, null, null,null, null, null, null,
null, null, null, null, null, null, null, null, null,
null, null, null,null, null, null)
SELECT Part_ID FROM tracking_vehicles
without the word "VALUES" as I saw many examples not use that, but it doesn't work. Even when I try my first example without "VALUES" it doesn't work either so I am guessing that I need that.

Using the example provided here I suggest you use the following syntax:
INSERT INTO Parts_list (_id, table_owner, etc)
SELECT null, 'My Name', etc
FROM tracking_vehicles
List out all your columns as I've started to and then pass through all the values in the SELECT.

Related

SQL Server export image to hardisc by iterating through fieldnames

We receive 10 images in varchar format through a mobile device app which are stored in one record of a table. The fields where the images are imported are named ImportPictureData, ImportPictureData2,...
[ID] [int] IDENTITY(1,1) NOT NULL,
[Projectnumber] [varchar](20) NULL,
[DeviceID] [nchar](20) NULL,
[Sendtime] [datetime] NULL,
[DeviceName] [nchar](30) NULL,
[ImportPictureData] [varchar](max) NULL,
[PictureData] [varbinary](max) NULL,
[ImportPictureData2] [varchar](max) NULL,
[PictureData2] [varbinary](max) NULL,
[ImportPictureData3] [varchar](max) NULL,
[PictureData3] [varbinary](max) NULL,
[ImportPictureData4] [varchar](max) NULL,
[PictureData4] [varbinary](max) NULL,
[ImportPictureData5] [varchar](max) NULL,
[PictureData5] [varbinary](max) NULL,
[ImportPictureData6] [varchar](max) NULL,
[PictureData6] [varbinary](max) NULL,
[ImportPictureData7] [varchar](max) NULL,
[PictureData7] [varbinary](max) NULL,
[ImportPictureData8] [varchar](max) NULL,
[PictureData8] [varbinary](max) NULL,
[ImportPictureData9] [varchar](max) NULL,
[PictureData9] [varbinary](max) NULL,
more of the importfields could be added.
To make the export flexible, I read the fieldnames in a table variable and try to create a dynamic SQL for the loop through the fields.
The SQL-string looks good where I create the string and print it(!) and then I try to assign the string to the variable which should recieve the image data:
set #sqlDynamicString='(Select Cast('''' AS XML).value(''xs:base64Binary(sql:column("'+ #PictureDateFieldName + '"))'', ''VARBINARY(MAX)'') FROM ScanIT_tblProjektbilder Where ID='''+ #PicID +''')'
creates this string:
(Select Cast('' AS XML).value('xs:base64Binary(sql:column("ImportPictureData"))', 'VARBINARY(MAX)') FROM ScanIT_tblProjektbilder Where ID='105')
DECLARE #ImageData VARBINARY(max);
select #ImageData = (Select Cast('' AS XML).value('xs:base64Binary(sql:column("ImportPictureData"))', 'VARBINARY(MAX)') FROM ScanIT_tblProjektbilder Where ID='105')
When I assign this string as a hardcopy to the variable #ImageData I do not get any error, if I am going to assign the variable #sqlDynamicString to the variable #ImageData like
select #ImageData = #sqlDynamicString
I get an
error 257: Implicit conversion from datatype 'VARCHAR' to 'VARBINARY(MAX)' is not allowed. Use CONVERT-Function
what is going wrong here??
Even using convert iso cast I get the same error.
Thanks
Execute the code in #sqlDynamicString,store the result in a temp table and then assign to your varbinary variable.
create table #temp
(
imageData varbinary(max)
)
insert into #temp
exec #sqlDynamicString
select #ImageData=(select imageData from #temp)

Firebird 2.5 insert row to existing table

I have table TABLE1 in a Firebird 2.5 database and want to insert multiple rows.
script:
INSERT INTO TABLE1 (ID, IDPREDEK, ICO, DIC, FIRMA, MISTO, ULICE, PSC, CISSML, CISEVID, PLATOD, PLATDO, JMENO, PRIJMENI, TITUL, FUNKCE, TELEFON, TELEFON2, FAX, EMAIL, ODP_JMENO, ODP_PRIJMENI, ODP_TITUL, ODP_FUNKCE, ODP_TELEFON, ODP_TELEFON2, ODP_FAX, ODP_EMAIL, D_INIDOP, D_INISETR, D_KATPRAC, POCETMUZI, POCETZENY, HASCHILD, HASCHILD1, HASCHILD2, POZNAMKA)
VALUES (91, 89, NULL, NULL, 'CLY0010702 - PHM-LPH_DEPO / PRG/RSM/FSB/PHM', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'N', 'N', 'N', NULL);
And problem is this error :
Error while importing to table TABLE1:
Engine Error (code = 335544665)
violation of PRIMARY or UNIGUE KEY constraint
"PK_TABLE1" on table "FIRMY".
Problematic key value is ("ID=95).
SQL Error (code= -803):
Invalid insert or update value(s): object columns are constrained - no 2 table rows can have duplicate column values.
In TABLE1 is last ID number 94, I don't have two same rows with ID 95.
Any ideas what to do?
Check is your ID identity. If so just leave it out of insert into() and values().
i found solution, replace ID :
... VALUES (GEN_ID(GEN_TABLE1 , 1), 91, NULL, NULL, ...

insert data in fixed length column sql server

I am trying to insert data in fixed length column but I am getting an error.
The table looks like this:
CREATE TABLE [dbo].[zam_pcinfo](
[Id] [decimal] identity NOT NULL,
[employe_name] [nvarchar](50) NOT NULL,
[location_id] [decimal] NOT NULL,
[department_id] [decimal] NOT NULL,
[computer_name] [nvarchar](25) NOT NULL,
[user_name] [nvarchar](25) NOT NULL,
[teamviewer_id] [nvarchar](25) NULL check (DATALENGTH(teamviewer_id) = 9),
[lan_ip] [nvarchar](20) NULL,
[policy] [nvarchar](25) NOT NULL,
[os] [nvarchar](25) NOT NULL,
[pctype] [nvarchar](25) NOT NULL,
[note] [nvarchar](50) NULL,
[password] [nvarchar](25) NOT NULL,
[tmngr] [bit] NOT NULL,
[type_user] [nvarchar] (25) Not null,
[w-internal-mac-address] [nvarchar](50) null)
I am using DATALENGTH function for teamviewer_id column, and when I am trying to insert data into this column it shows this error:
insert statement is conflict with check constraint "nameoftheconstraint" the conflict occurred in database "nameofdatabase", table "nameoftable" column teamviewer_id
Can you help me in that? And is the check constraint is right in this situation?
i use Len instead and its work , thank you

Auditing trigger - Column name or number of supplied values does not match table definition

I am attempting to create a database trigger capable of creating a snapshot of a 'Transactions' table and storing it in an 'Audit' table along with information pertaining to the date of the inserting, updating or deleting of any rows of data.
Apologies in advance, but I'm very much a novice at this kinda stuff!
As it stands, my trigger is as follows:
create trigger AuditTransactions
on dbo.Transactions
after insert, update, delete
as
if exists(select * from inserted)
begin
if exists(select * from deleted)
begin
-- this is for an update
update Audit
set DeleteDate = getdate()
where TransactionId in (select TransactionId from deleted)
end
-- this is just for an insert
insert into Audit
select *, getdate() as CreateDate
from inserted
end
else
begin
-- this is just for a delete
update Audit
set DeleteDate = getdate()
where TransactionId in (select TransactionId from deleted)
end
go
And my audit table appears as follows:
CREATE TABLE [dbo].[Audit](
[TransactionId] [int] NOT NULL,
[InvoiceNumber] [nvarchar](1) NULL,
[InvoiceType] [nvarchar](1) NULL,
[InvoiceIssueDate] [datetime] NULL,
[InvoiceTotalexclVat] [nvarchar](1) NULL,
[InvoiceTotalVat] [numeric](18, 0) NULL,
[InvoiceDiscount] [numeric](18, 0) NULL,
[InvoiceTotalPayable] [numeric](18, 0) NULL,
[AccountCode] [nvarchar](1) NULL,
[Reference1] [nvarchar](1) NULL,
[Reference2] [nvarchar](1) NULL,
[Reference3] [nvarchar](1) NULL,
[Level1CustomOrg] [nvarchar](1) NULL,
[Level2CustomOrg] [nvarchar](1) NULL,
[Level3CustomOrg] [nvarchar](1) NULL,
[Level4CustomOrg] [nvarchar](1) NULL,
[ScanLocation] [nvarchar](1) NULL,
[ScanDateTime] [datetime] NULL,
[CaptureInkjetId] [nvarchar](1) NULL,
[CaptureBatchId] [nvarchar](1) NULL,
[CaptureDateTime] [datetime] NULL,
[InputSource] [nvarchar](1) NULL,
[CurrencyCode] [nvarchar](1) NULL,
[DebitCredit] [nvarchar](1) NULL,
[OrderNumberHeader] [nvarchar](1) NULL,
[SupplierName] [nvarchar](1) NULL,
[BancPaySupplierId] [nvarchar](1) NULL,
[SupplierIDERP] [nvarchar](1) NULL,
[PaymentDate] [datetime] NULL,
[DeliveryDate] [datetime] NULL,
[CustomRef1] [nvarchar](1) NULL,
[CustomRef2] [nvarchar](1) NULL,
[CustomRef3] [nvarchar](1) NULL,
[CustomRef4] [nvarchar](1) NULL,
[CustomRef5] [nvarchar](1) NULL,
[CustomRef6] [nvarchar](1) NULL,
[CustomRef7] [nvarchar](1) NULL,
[CustomRef8] [nvarchar](1) NULL,
[CustomRef9] [nvarchar](1) NULL,
[CustomRef10] [nvarchar](1) NULL,
[CustomRef11] [nvarchar](1) NULL,
[CustomRef12] [nvarchar](1) NULL,
[CustomRef13] [nvarchar](1) NULL,
[CustomRef14] [nvarchar](1) NULL,
[CustomRef15] [nvarchar](1) NULL,
[CustomAmount1] [numeric](18, 0) NULL,
[CustomAmount2] [numeric](18, 0) NULL,
[CustomAmount3] [numeric](18, 0) NULL,
[CustomAmount4] [numeric](18, 0) NULL,
[CustomAmount5] [numeric](18, 0) NULL,
[CustomDate1] [datetime] NULL,
[CustomDate2] [datetime] NULL,
[Country1] [nvarchar](1) NULL,
[Country2] [nvarchar](1) NULL,
[Country3] [nvarchar](1) NULL,
[Country4] [nvarchar](1) NULL,
[Country5] [nvarchar](1) NULL,
[Country6] [nvarchar](1) NULL,
[Country7] [nvarchar](1) NULL,
[Country8] [nvarchar](1) NULL,
[Country9] [nvarchar](1) NULL,
[Country10] [nvarchar](1) NULL,
[CheckedOut] [bit] NULL,
[CheckedOutDate] [datetime] NULL,
[BlobUrl] [nvarchar](1) NULL,
[GLCode] [nvarchar](1) NULL,
[RejectReason] [nvarchar](1) NULL,
[RejectComment] [nvarchar](1) NULL,
[ReferMessage] [nvarchar](1) NULL,
[PaymentTerms] [nvarchar](1) NULL,
[CheckedOutByUserId] [int] NULL,
[LastUpdatedByUserId] [int] NULL,
[TransactionFormatTypeId] [int] NULL,
[RequestOriginalStatusTypeId] [int] NULL,
[GLCodeComment] [nvarchar](1) NULL,
[SenderOrganizationId] [int] NULL,
[ReceiverOrganizationId] [int] NULL,
[TransactionStatusTypeId] [int] NULL,
[TransactionTypeId] [int] NULL,
[OrganizationId] [int] NULL,
[OrganizationId1] [int] NULL,
[CreateDate] [datetime] NOT NULL,
[DeleteDate] [datetime] NULL
) ON [PRIMARY]
GO
When attempting to execute the query for the trigger I am getting the following error message:
Msg 213, Level 16, State 1, Procedure AuditTransactions, Line 17
Column name or number of supplied values does not match table definition.
This appears to be the 'insert into Audit' command, but I have no idea what to do from here!
Any help will be hugely appreciated, thanks in advance!
INSERT seems to be rather poorly documented. For the VALUES() element, it states the following:
If the values in the Value list are not in the same order as the columns in the table or do not have a value for each column in the table, column_list must be used to explicitly specify the column that stores each incoming value.
(Emphasis added)
However, it is my understanding and belief that the same constraint applies, no matter what the source of values/rows are - that unless you exactly match all columns in the table, you need to provide the column_list.
Now, for your instance, it may be easier if you just provide a value for every column in the table:
insert into Audit
select *, getdate() as CreateDate,null as DeleteDate
from inserted
Now, my other observation is that all this mucking about with conditional control flow is rather pointless - an insert of 0 rows will have no effect, and an update using in against an empty table will similarly have no effect. So I'd just have:
create trigger AuditTransactions
on dbo.Transactions
after insert, update, delete
as
update Audit
set DeleteDate = getdate()
where TransactionId in (select TransactionId from deleted)
insert into Audit
select *, getdate() as CreateDate,null as DeleteDate
from inserted
insert into Audit
select *, getdate() as CreateDate, null
from inserted
Your "audit" table has more columns than you're inserting (the deleted date); you need to either name all the columns, or insert a null.
Stylistically, naming the columns is better - it makes it clear what goes where, and avoid bugs when you add new columns.

Joining multiple columns in one table to a single column in another table

I am looking to create a view that pulls data from two tables "Schedule" and "Reference".
Schedule has 50+ columns (it's almost completely denormalized -- not my design), most of which contain a value that could be joined to a column in the Reference table.
How do I write the SQL statement to correctly join each column in Schedules to the single column in Reference?
The Schedule table is defined as:
CREATE TABLE [dbo].[Schedule](
[ID] [int] NOT NULL,
[SCHEDULEWEEK] [datetime] NOT NULL,
[EMPNO] [numeric](10, 0) NOT NULL,
[EMPLNAME] [varchar](32) NULL,
[EMPFNAME] [varchar](32) NULL,
[EMPSENDATE] [datetime] NULL,
[EMPHIREDATE] [datetime] NULL,
[EMPTYPE] [char](1) NULL,
[EMPSTATUS] [char](1) NULL,
[SNREFUSALS] [tinyint] NULL,
[QUALSTRING] [varchar](128) NULL,
[JOBOVERSHIFTTYPE] [bit] NULL,
[SHORTNOTICE] [bit] NULL,
[SHORTNOTICEWAP] [bit] NULL,
[SHORTNOTICEPHONE] [varchar](32) NULL,
[LEADHAND] [bit] NULL,
[DUALCURRENCY] [bit] NULL,
[MIN100WINDOW] [bit] NULL,
[STATHOLIDAY] [bit] NULL,
[AREAOVERHOURS] [bit] NULL,
[DOUBLEINTERZONES] [bit] NULL,
[MAXDAYSPERWEEK] [tinyint] NULL,
[MAXHOURSPERWEEK] [numeric](10, 2) NULL,
[MAXHOURSPERSHIFT] [numeric](10, 2) NULL,
[MAXDOUBLESPERWEEK] [tinyint] NULL,
[ASSIGNEDDAYS] [tinyint] NULL,
[ASSIGNEDHOURS] [numeric](10, 2) NULL,
[ASSIGNEDDOUBLES] [tinyint] NULL,
[ASSIGNEDLOAHOURS] [numeric](10, 2) NULL,
[SHIFTNO1] [int] NULL,
[TEXT1_1] [varchar](64) NULL,
[TEXT2_1] [varchar](64) NULL,
[DAYFLAG1] [bit] NULL,
[COMMENT1] [text] NULL,
[SHIFTNO2] [int] NULL,
[TEXT1_2] [varchar](64) NULL,
[TEXT2_2] [varchar](64) NULL,
[DAYFLAG2] [bit] NULL,
[COMMENT2] [text] NULL,
[SHIFTNO3] [int] NULL,
[TEXT1_3] [varchar](64) NULL,
[TEXT2_3] [varchar](64) NULL,
[DAYFLAG3] [bit] NULL,
[COMMENT3] [text] NULL,
[SHIFTNO4] [int] NULL,
[TEXT1_4] [varchar](64) NULL,
[TEXT2_4] [varchar](64) NULL,
[DAYFLAG4] [bit] NULL,
[COMMENT4] [text] NULL,
[SHIFTNO5] [int] NULL,
[TEXT1_5] [varchar](64) NULL,
[TEXT2_5] [varchar](64) NULL,
[DAYFLAG5] [bit] NULL,
[COMMENT5] [text] NULL,
[SHIFTNO6] [int] NULL,
[TEXT1_6] [varchar](64) NULL,
[TEXT2_6] [varchar](64) NULL,
[DAYFLAG6] [bit] NULL,
[COMMENT6] [text] NULL
-- Snip
) ON [PRIMARY]
And the Reference table is defined as:
CREATE TABLE [dbo].[Reference](
[ID] [int] NOT NULL,
[CODE] [varchar](21) NOT NULL,
[LOCATIONCODE] [varchar](4) NOT NULL,
[SCHAREACODE] [varchar](16) NOT NULL,
[LOCATIONNAME] [varchar](32) NOT NULL,
[FLTAREACODE] [varchar](16) NOT NULL
) ON [PRIMARY]
I am trying to join each [TEXT1_]/[TEXT2_] column in Schedule to the [SCHAREACODE] column in reference. All the reference table contains is a list of areas where the employee could work.
I think he means to join on the Reference table multiple times:
SELECT *
FROM Schedule AS S
INNER JOIN Reference AS R1
ON R1.ID = S.FirstID
INNER JOIN Reference AS R2
ON R2.ID = S.SecondID
INNER JOIN Reference AS R3
ON R3.ID = S.ThirdID
INNER JOIN Reference AS R4
ON R4.ID = S.ForthID
Your description is a bit lacking, so I'm going to assume that
Schedule has 50+ columns (it's almost completely denormalized -- not my design), most of which contain a value that could be joined to a column in the Reference table.
means that 1 of the 50+ columns in Schedule is a ReferenceId. So, given a table design like:
Schedule ( MaybeReferenceId1, MaybeReferenceId2, MaybeReferenceId3, ... )
Reference ( ReferenceId )
Something like:
SELECT *
FROM Schedule
JOIN Reference ON
Schedule.MaybeReferenceId1 = Reference.ReferenceId
OR Schedule.MaybeReferenceId2 = Reference.ReferenceId
OR Schedule.MaybeReferenceId3 = Reference.ReferenceId
OR Schedule.MaybeReferenceId4 = Reference.ReferenceId
...
would work. You could simplify it by using IN if your RDBMS supports it:
SELECT *
FROM Schedule
JOIN Reference ON
Reference.ReferenceId IN (
Schedule.MaybeReferenceId1,
Schedule.MaybeReferenceId2,
Schedule.MaybeReferenceId3,
Schedule.MaybeReferenceId4,
...
)
From updated question
Perhaps something like this? It will be messy no matter what you do.
SELECT S.ID
S.TEXT1_1,
TEXT1_1_RID = COALESCE((SELECT MAX(R.ID) FROM Reference R WHERE R.SCHAREACODE = S.TEXT1_1), 0),
S.TEXT1_2,
TEXT1_2_RID = COALESCE((SELECT MAX(R.ID) FROM Reference R WHERE R.SCHAREACODE = S.TEXT1_2), 0),
...
FROM Schedule S
Agree with TheSoftwareJedi, but can I just suggest using LEFT JOINs so that failures-to-match don't cause your Schedule row to disappear?
Of course, doing 28 JOINs is going to be a bit cumbersome whatever the details.
I'm not sure I'd call this "denormalized", more "abnormalized" ... :-)
Try a query like this:
select s.*, r.schareacode from schedule s,
where
s.text1_1 = s.schareacode
or s.text2_1 = s.schareacode
or s.textx_x = s.schareacode
..
You should be able to get the same results with traditional joins so I recommend you experiment with that as well.