Ok, I have a table that contains a number of columns, one of these columns contains a 'unitref' e.g.AC02/001D.
I import a new set of records, approx 7,000 per week in a DTS package from CSV Flat File into the table.
What I need to achieve at either the point of import of new data weekly, or once the new data is sitting in its final resting home, is a copy of the first two 2 Chars of the UnitRef, in the example above, this would make it 'AC' and then place that in a column named 'site_ref'.
Having posted the question on this forum relating to grabbing the first two chars of a value and placing them in a temporary table by utilising the Left(field,2) command in SQL (Kindly answered by CryptoKnight), I was wondering how I can do this possibly by using the inesrt into type command. I have many columns that get imported this is only a tiny step of many things that ideally would need to happen on an import,
Hi I am having two very basic problems which are very frustrating. I have read http://blogs.msdn.com/smartclientdata/archive/2005/08/26/456886.aspx and changed my DB to "Copy if newer" however when I use the connection string "|DataDirectory|MyDB.sdf" MyDB remains unchanged. (If I put the full path to MyDB in the connection string I will see the changes.) I have tried copying the DB file in the bindebug directory and opening the copy separately, and the changes still do not appear.
This leads me to my second issue. While trying to verify if the insert worked, I am trying to query the DB for the row I just inserted. I have found very little documentation describing how to do this; am I missing something/someplace obvious? Here is my code:
string strCommand = "SELECT * FROM Log WHERE Severity = @Sev AND Message = @Msg"; SqlCeResultSet resultSet = null; SqlCeCommand sqlCommand = new SqlCeCommand(strCommand, pConn);
resultSet always returns non-null, so I am clearly doing something wrong. Do I need to "read through" the resultSet to make sure there is something there? And if so, how? Should I be using a DataReader instead? (and if so how?) Am I going in the wrong direction? Just to be clear, I want to insert a row into my DB and then check that that row has been inserted by querying the DB.
i am just trying to insert a title and category row into a table in my database, however, the page works as planned, bu no data is inserted, and i am not getting any error messages, so i am for a loss.
If I have Table1 with ClientID (int) <primaryKey> (set to auto increment), ClientName (varchar50) Table2 with ColorID (int) <primaryKey> (set to auto increment) ColorName (varchar50) ClientID (int) <relatedForeignKey> What I want to do is.... 1. Click on a select link on the gridview on Page1 which contains records from Table1 2. Page1 closes and Page2 opens and displays in a gridview all the Colors from Table2, that are related by ClientID on Table1, based on the selection on Page1 which is set up by passing a query string that Queries Table2 on Page2. 3. User selects, via 'Select' link on the gridview, a record and a detailsForm in Insert mode displays below the gidview. 4. User fills in ColorName and clicks on Insert. ERROR. System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ClientID', table 'C:DOCUMENTS AND SETTINGSOWNERDESKTOPWEBSITE3APP_DATADATABASE.MDF.dbo.Table2'; column does not allow nulls. INSERT fails.The statement has been terminated.I don't want to have to type in the related ForeignKey value. I want the value to be automatically recognized as the value of the PrimaryKey value. I don't know how to do this. I'm not very efficient when reading or writing code, so as much explanation and description as you can offer would be most appreciative. thanks so much....good luck to me!
I created an application using Access and converted it to a MS SQL database - it worked well in access but I'm now having troubles with it in MS SQL - even just doing a simple insert.
To locate the problem, I created a simple table "Member" with only one field "FirstName" - a page with only one form field "FirstName" which goes to regchk.asp which has this code: <% strconn = "Provider=SQLOLEDB; " strconn = strconn & "Data Source=PHSSQLWEBRPD2; " strconn = strconn & "Initial Catalog=OPRS; " strconn = strconn & "User Id=MYUSERIDHERE; " strconn = strconn & "Password=MYPASSWORDHERE"
Set conn = Server.CreateObject("ADODB.Connection") conn.ConnectionString = strconn conn.Open
strSQL1 = "SELECT * " & _ "FROM Member"
Set rs = conn.Execute(strSQL1) If rs.BOF AND rs.EOF Then
I'm new to using MS SQL Server 2005, having only worked with MySQL in the past.
If some kind person could please tell me what the equivelant MS SQL syntax should be for the MySQL query shown below then I can work everything else out for myself. I just need this hand up to get going on my MS SQL adventure. TIA.
I am developing a program on Visual Basic 2005 to a pocket pc, I want to make the SQLceconnection but It says that the file doesnīt exists, I use this code:
I need to insert a sparkline based on values in columns. I cannot insert a image - seems my account must be verified (whatever that means).Basically what I need is a sparkline that is created based on columns for each row. Like in Excel.I have seen a similiar question here URL.. forum=sqlreportingservices).
Suppose we get two following tables: Table A: [USER_ID] [varchar] (11) NOT NULL , [COURSE_ID] [varchar] (11) NOT NULL , Table B: [COURSE_ID] [varchar] (11) NOT NULL , [COURSE_NAME] [varchar] (50) NOT NULL , [COURSE_NO] [varchar] (15) NULL , [BEGIN_DATE] [datetime] NULL , [END_DATE] [datetime] NULL , [CREATER] [varchar] (11) NOT NULL , and during the execution of my program, I can get the current use's id (USER_ID), say U0001. How can I retrieve the result set containing [COURSE_NAME], [COURSE_ID], but the current user's id (U0001) have Not been assigned in Table A. Thanks in advance. Ricky.
I'm not getting it. The query below "e.g." is exactly as I think it should be except for the <Join Clause> as there is only the match on site name. I tried joing on the site name, but only got the sites in the log. I want all the site names even if they don't have a log item for a given date range.
I'd post my real query if it would help, it's just that I'm chopping up some strings and converting some time stamps to dates as varchar for readability for the final report, which is an MSExcel pivot table.
My original post lies below.
TIA
jEfFp...
Reply... Date: Basic Query Help (reply) RickD (Rick.Davis@Schroders.com) 7/11/01 6:41:26 AM
Make log an outer join to site.
e.g
select s.name, l.ondate from site s RIGHT OUTER JOIN log l ON <Join Clause> where substring(id,3,6) in(select name from site) and ondate between getdate()-8 and getdate()-1
You didn't seem to have any logical join between the tables, but i'm sure you have, just put this in the <Join Clause>.
Oh, and read BoL, it helps no end.....
------------ Original Post... Jeff Proctor at 7/10/01 11:18:31 PM
my 7 day query....
select s.name, l.ondate from site s, log l where substring(id,3,6) in(select name from site) and ondate between getdate()-8 and getdate()-1
This returns those sites that exist in the current log, however what I want is a result set that has a row for each name regardless if they are in the log.
I have 2 tables...
table1 sites name smithj anandt burtot proctj etc....
I am trouble getting the count of applications. In the below query MerApp.ApplicationID represents the applications. I'm trying to get a results of a count of applications for each sales team member.Before adding the COUNT() function. My query results show 3811 because it shows the sales team member numerous times because he has many applications with different IDs. For example sales team member A shows up in 75 rows because he has 75 different applications assigned to him.
SELECT (usr.FirstName + '' + usr.LastName)AS [Sales Team Member], MerApp.Assignedto, MerApp.ApplicationID, stm.UserID, MerApp.ActiveStatus FROM MerchantApplication MerApp INNER JOIN Users usr ON MerApp.assignedTo = usr.UserID INNER JOIN SalesTeamMembers stm ON usr.UserID = stm.UserID WHERE MerApp.ActiveStatus=1 GROUP BY MerApp.AssignedTo, usr.LastName, usr.FirstName, MerApp.ApplicationID, stm.UserID, MerApp.ActiveStatus
I want sales team member A to show up once with the count of applications to be 75 because that's how many are assigned to him.
This didn't work for me: SELECT (usr.FirstName + '' + usr.LastName)AS [Sales Team Member], MerApp.Assignedto, COUNT (MerApp.ApplicationID) AS [Applications], stm.UserID, MerApp.ActiveStatus FROM MerchantApplication MerApp INNER JOIN Users usr ON MerApp.assignedTo = usr.UserID INNER JOIN SalesTeamMembers stm ON usr.UserID = stm.UserID WHERE MerApp.ActiveStatus=1 GROUP BY MerApp.AssignedTo, usr.LastName, usr.FirstName, MerApp.ApplicationID, stm.UserID, MerApp.ActiveStatus
It didn't count the number of applications for each person.I have about 14 different sales team members. So I'm trying to have a query that produces 14 rows not 3811 rows
ARRRRRRRGGGGGHHHHH!!Please can you help, I'm going round the bend with this.I have a simple and small table called STOCKCATS, which I need to query toget back a dataset in a particular order, but although it looks simple Ican't get it to work. My table schema plus sample data to see the problemis as follows:DROP TABLE IF EXISTS `STOCKCATS`;CREATE TABLE `STOCKCATS` (`CATID` varchar(30) NOT NULL default '',`LEVEL` varchar(30) default NULL,PRIMARY KEY (`CATID`),KEY `indxCATEGORYID` (`CATID`));INSERT INTO `STOCKCATS` (`CATID`,`LEVEL`) VALUES('A001',''),('A002','A001'),('A003','A001'),('A004','A001'),('A005','A001'),('PCHW01',''),('MHW01',''),('FD01',''),('ELEC01',''),('MHW02','MHW01');INSERT INTO `STOCKCATS` (`CATID`,`LEVEL`) VALUES('MHW03','MHW01'),('MHW04','MHW01'),('MHW05','MHW01'),('PCHW02','PCHW01'),('PCHW03','PCHW01'),('PCHW04','PCHW01'),('PCHW05','PCHW01'),('PCSW01',''),('MSW01',''),('C001',''),('C002','C001'),('C003','C001'),('MV',''),('SUZ','MV'),('ALF','MV'),('PLASMA','ELEC01'),('T01','ELEC01'),('HEATING',''),('RAD','HEATING'),('P01',''),('B01','P01'),('BB','HEATING'),('FS','HEATING'),('WM','HEATING'),('AEROSOL',''),('SOLVENTS','AEROSOL'),('DGC','');INSERT INTO `STOCKCATS` (`CATID`,`LEVEL`) VALUES('DGXWINDOWS','DGC'),('DGXEXTRA','DGC'),('DGXCON','DGC');As you can see from the table structure, this table consists of 2 fieldvalues. The 1st is the category code and the 2nd is the level is at. If acatid has a level of nothing, eg '', then it means that it is a root levelcategory. If a catid has a another cat's catid in it's level, eg B01 hasP01, then it is a sub-category of this category, eg B01 is a sub-cat of P01.All I want to do is query this table and bring back the data so thatalphabetically it goes root level cat A1, then all the sub-cats for thisroot level, then root level A2, then all sub-cats for this root level and soon. An example using the above would be as follows:^ ^ A to G of root level cats plus their sub-cats....HEATING << root levelBB << sub-cat of heatingFS << sub-cat of heatingWM << sub-cat of heating/ / I to Z of root level cats plus their sub-cats....A few posters kindly gave me a solution of ORDER BY COALESCE(CATID,LEVEL),CATID and I thought this had done it, but I was looking at the ('A001',''),('A002','A001'), ('A003','A001'), ('A004','A001'), ('A005','A001')entries as these naturally fell into place. If you use this order commandon the above you will see that ('P01','') and it's associated ('B01','P01')sub-cat just don't come together.Does any body have any ideas?ThanksLaphan
Ok, I'm a beginner so forgive me for my ignorance. Could someone helpme with this?tbl_x has two fields xid and xlistxlist being a list of numbers.....1, 5, 6, 8i want to create a new table from tbl_x that converts each number inthat xlist into a row in tbl_newso for exampletbl_x has 3 rowsxid xlist1 1, 4, 52 2, 3, 73 2, 1, 7i need a query or sql script that will convert that table with a listinto the following....tbl_newid xid xlid1 1 12 1 43 1 54 2 25 2 36 2 77 3 28 3 19 3 7
How would I convert this query to ANSI 92 standard?
select p.InternalID, n.LastName from tblPatient p, tblName n where p.PatientID = n.EntID and n.EffDt = ( select max(n2.EffDt) from tblName n2 where n.EntID = n2.EntID and n2.EffDt <= getdate() )
i am learning SQL basic commands ( like , where, having, group by, order by , join ,and simple sub-query) and I got one exersice I cannot solve
table RECIPE has 3 columns , ( pizza ,ingredient,amount) each pizza could use 1 / many ingredient, each ingredient could be used by 0 / 1/ many pizza, amount means the quantity of that ingredient used in certain pizza
question: (List the ingredients, and for each ingredient, also list the pizza that contains the largest amount of this ingredient.)
============================ Raw data :
recipe ====== pizza ingredient amount -------------------------------- margarita spice 5 margarita cheese 120 ham ham 150 ham spice 5 napolitana anchovies 100 napolitana olives 75 napolitana spice 10 hawaiian ham 100 hawaiian pineapple 100 hawaiian spice 5 cabanossi cabanossi 150 cabanossi spice 10 siciliano onion 50 siciliano capsicum 75 siciliano olives 50 siciliano anchovies 50 siciliano spice 15 americano salami 120 americano pepperoni 75 americano spice 10 mexicano onion 75 mexicano capsicum 75 mexicano mushroom 50 mexicano chilli 25 mexicano spice 20 seafood seafood 200 seafood spice 5 garlic garlic 25 garlic spice 10 vegetarian onion 50 vegetarian capsicum 50 vegetarian mushroom 50 vegetarian peas 50 vegetarian tomato 50 vegetarian spice 5 mushroom mushroom 100 mushroom spice 5 special cheese 25 special tomato 25 special ham 25 special anchovies 25 special olives 25 special mushroom 25 special bacon 25 special egg 25 special pineapple 25 special cabanossi 25 special salami 25 special capsicum 25 special onion 25 special peas 25 special seafood 25 special spice 10 stagiony ham 75 stagiony mushroom 50 stagiony olives 50 stagiony anchovies 25 stagiony spice 10
Hi,I feel stupid for posting this question but I cannot find out how to create an SQL statement to return records that have been added today.My database table has a field called calldate which hold the date and time of the record added to the database i.e. "02/08/2005 16:55:41".Please can someone let me know how I can search to find all records added today. I thought it would be something like it, but I assume I need to format the calldate so it's just 02/08/2005.Select *From TableWhere CallDate = GetDate()ThanksBrett
I am having some difficulty writing a relatively basic query. The objective is to retrieve the new stories (headlines) for the past 3 days from the database. Since each headline can be assigned multiple categories (topics) the query returns a row for every headline assignment. I can't use the 'Group By' expression because one of the columns is nText.
So basically if there is an article written yesterday, "I Love Cats" that gets assigned both topics 'CATS' and 'PETS' I only it returned with the first topic assigned... 'CATS'. Here is a little image of the three tables being called:
http://64.225.154.232/temp_dbDiagram.gif
I don't think that this query is too difficult, but I'm just getting my feet wet with writing queries that are more than select * from whatever. Any insight or recommendations are greatly appreciated.
SELECT headline.HEADLINE_ID, headline.HEADLINE_TITLE, headline.HEADLINE_DATE, headline.HEADLINE_THUMBNAIL, topic.TOPIC_NAME, topic.TOPIC_URL FROM tbl_CCF_Headlines headline INNER JOIN tbl_CCF_Headlines_Topics ON headline.HEADLINE_ID = tbl_CCF_Headlines_Topics.HEADLINE_ID INNER JOIN tbl_CCF_Topics topic ON tbl_CCF_Headlines_Topics.TOPIC_ID = topic.TOPIC_ID WHERE (headline.HEADLINE_DATE IN (SELECT TOP 3 HEADLINE_DATE FROM tbl_CCF_HEADLINES GROUP BY HEADLINE_DATE ORDER BY HEADLINE_DATE DESC)) ORDER BY headline.HEADLINE_DATE DESC
A123456789 THOMAS, CHARLES B. 009/11/01 M05/04/511G
I want to run that data through some substrings etc. and dump it into another table like this:
//THIS TABLE WILL BE WHERE WE PUT THE RESULTING DATA FROM //EXECUTING THE SUBSTRs AND OTHER FUNCTIONS TO PREP THE DATA FOR BASIS. CREATE TABLE ISIS_DATA_PREP (ISIS_STATUS_ID VARCHAR(15), STATUS VARCHAR(5), STUDENT_ID NUMERIC(15) CONSTRAINT ISIS_DATA_PREP_STUDENT_ID_PK PRIMARY KEY, LAST_NAME VARCHAR(25), FIRST_NAME VARCHAR(20), MID_INIT CHAR(1), CLASS NUMERIC(2), EXPIR_DATE VARCHAR(10), SEX CHAR(1), BIRTHDAY VARCHAR(10), CAT NUMERIC(3), SCHOOL VARCHAR(5))
Server: Msg 8114, Level 16, State 5, Line 1 Error converting data type varchar to numeric.
QUESTION #1 - Is there an equivalent in MS SQL 2000 to Oracle's TONUM function?
So, to get around this I change all the fields in the receiving table (ISIS_DATA_PREP) to a varchar so there is no conversion necessary at this time.
Now I get this message:
Server: Msg 8152, Level 16, State 9, Line 1 String or binary data would be truncated. The statement has been terminated.
I look up this error on MS's knowledge base and get something along these lines:
...Because the truncated string is shorter than the maximum length, the char column that does not allow a null value and the char variable is padded with trailing blanks while the varchar column will not store trailing blanks....
QUESTION #2 -
What am I doing wrong on the field structure on the receiving table of the input command? I experimented by setting all fields to VARCHAR(25) so it would accept more data and not truncate, but still get the same message.
QUESTION #3 - My main question was for the syntax for INSERTing into a table from another table the rows in MS SQL. Basically copying the data. I have it for Oracle, but MS SQL doesn't seem to take it in that format.
Sorry for the absolutely massive post. : ) And thanks for any feedback.
Can I roll back certain query(insert/update) execution in one page if query (insert/update) in other page execution fails in asp.net.( I am using sqlserver 2000 as back end) scenario In a webpage1, I have insert query into master table and Page2 I have insert query to store data in sub table. I need to rollback the insert command execution for sub table ,if insert command to master table in web page1 is failed. (Query in webpage2 executes first, then only the query in webpage1) Can I use System. Transaction to solve this? Thanks in advance
i want to implement something like let say i have 2 table...customer table and order table....order table has a foreign key of customer table (maybe the customer_id)...is there any way that let say, i want to insert a particular customer_id in the customer table. Then, it will insert the particular customer_id in the order table also. I want to make one statement query that can solve that situation?
my application will add and delete and update records in db my problem is when to insert I have one text box and one dropdownbox one to write the name of db and the dropdownbox to choose the holding server ..
this is the structure of each table >> servers_tbl : SRV_ID,Server_Name DB_tbl : DB_ID,DB_Name srvdb_tbl : DB_ID,SRV_ID(forign keys from the previous tables) so >>> I want to add a new db to a server so I am writing the new db name in the textbox and choose the server from the dropdownbox and press a button to add the db name in the DB_tbl.DB_Name and add the db id in the DB_tbl.DB_ID to the srvdb_tbl.DB_ID and server id in the Servers_tbl.SRV_ID any one can help me ....
Hi All! I really need to pick your brains for a moment. I am attempting to create a INSERT INTO query that will select recrods from another existing table. This part can figure out... INSERT INTO "table1" ("column1", "column2")SELECT "column1", "column2"FROM "table2" Easy enough, but my table1 contains additional fields that the select statement does not retrieve from table2 (lets say "column3" and "column4"). I want to statically assign values to column3 and 4 at the same time. "column3" = Yes "column4" = No is there a way to do this within the same insert statement? Thanks for all your help!
can somebody help me in this plz m new to .net...m using visual studio 2005 how do we write this query actually...Dim con As SqlConnection = New SqlConnection("Server=;uid=;pwd=;Database=") Dim ra As Integer con.Open() myCommand = New SqlCommand("Insert into Telecheck(DateCheck,Hospital,Ward,PhoneNumber,StaffName,StatusOfStaff,StatusOfPhone)values(getdate(),'" & ComboBox1.SelectedItem.text & "','" & ComboBox3.SelectedItem.text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & ComboBox4.SelectedItem.text & "','" & ComboBox2.SelectedItem.text & "') ", con) ra = myCommand.ExecuteNonQuery() MessageBox.Show("Record entered") con.Close() the above is the code for windows here i am getting an error which says "{"Public member 'text' on type 'String' not found."}"the type of database is sqlserver 2000 and the type of column are nvarchar,only date is datetime
Declare @UID intDeclare @FID varchar(50)set @UID = 1set @FID = '1,2,3'insert into table_name (UID,FID) values(@UID,'+@FID+') Can we have an insert query like above or is their another way to get the result like below the result should beUID FID 1 1 1 2 1 3
I am needing to insert two values from tables, one would be from a query, which is easy, one needs to be static, easy. The not easiness (not a word) comes from combining the two. Here would be an example of what I am trying to run...
Code:
insert into MEMBER_SUBSCRIPTION_CHANNEL_FORMAT (MEMBER_ID,SUBSCRIPTION_CHANNEL_FORMAT_ID) (select m.MEMBER_ID from MEMBER m,MEMBER_SUBSCRIPTION ms where m.MEMBER_ID = ms.MEMBER_ID and m.SUBSCRIPTION_FORMAT_ID = 1 and ms.SUBSCRIPTION_ID = 1), 1
the last part of the code ', 1' would be the static part. Any ideas?
Hi guys I need to insert some updated Terms from another table but it keeps telling me that it cant because it would be creating duplicates. The funny thing about it is I did a comparison with the two tables one table is called UpdateForTerms Table and the other is called TERMINATION
SELECT UpdateForTerms.EMPLOYEE, UpdateForTerms.EMP_STATUS, UpdateForTerms.TERM_DATE, UpdateForTerms.DEPARTMENT, UpdateForTerms.LAST_NAME, UpdateForTerms.FIRST_NAME, UpdateForTerms.DESCRIPTION FROM UpdateForTerms LEFT JOIN TERMINATION ON UpdateForTerms.EMPLOYEE = TERMINATION.[TM #] WHERE (((TERMINATION.[TM #]) Is Null));
I made the results of this into a query so I could update the Termination table. The reason I created this query is so that I could weed out those records the Terminations table already had. Kind of a futile attempt it seems
I've been going around in circles and was wondering if anyone could help with this insert query. (I'm using SQL Server 2005).
I have two tables aspnet_Users and aspnet_Draws. They have a 1 to many relationship, with UserID being the PK in aspnet_Users and the FK in aspnet_Draws. Table structure is:
aspnet_Draws ID (PK) UserId DrawDate NumberOfEntries
aspnet_Users UserId (PK) UserName
I want to insert a row into aspnet_Draws. UserID needs to be taken from aspnet_Users where UserName is a particular value, e.g. NameXXX
DrawDate and NumberOfEntries do not allow nulls and also need to be updated, though these values will be taken from a webForm and not from aspnet_Users. ID is automatically incremented.
Basically, what is the best method, ie. not in, left join, etc to write this insert query? I feel like I know this, but mostly I want to make sure I am using the most efficient way. There are 1.1M records in the first table, named Complete_Products, and 979K in tblProducts. I already ran the update query that selected on the ProductCode column in both that updated tblProduct for the records that were also in Complete_Products. That ran fine, a bit long, but it worked and updated the 805,273 records they had in common. Now I need to insert the new records that are in Complete_Products that are not in tblProducts.
IF OBJECT_ID('dbo.InsITRRComments') IS NOT NULL BEGIN DROP PROCEDURE dbo.InsITRRComments IF OBJECT_ID('dbo.InsITRRComments') IS NOT NULL PRINT '<<< FAILED DROPPING PROCEDURE dbo.InsITRRComments >>' ELSE PRINT '<<< DROPPED PROCEDURE dbo.InsITRRComments >>' END go SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS OFF GO
INSERT INTO ITRRComments VALUES ( @DacType, @DacTypeId, @TypeOfComment, @Comments, @RiskId_External_ID, @UserId, (select FullUserName from SecurityUsers where UserId=@UserId) @AmendedDateTime, 'N' ) END
GO
IF OBJECT_ID('dbo.InsITRRComments') IS NOT NULL PRINT '<<< CREATED PROCEDURE dbo.InsITRRComments>>>' ELSE PRINT '<<< FAILED CREATING PROCEDURE dbo.InsITRRComments>>>' go
GRANT EXECUTE ON dbo.InsITRRComments TO AppWrite go
SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO
Subqueries are not allowed in this context. Only scalar expressions are allowed
This is the error that I'm getting, how do I get round the issue of a sub query problem
How do I use Enterprise manager to insert records from one table into a blank table ? I open my table (with data) as a query and change it to an Insert From query but it doesn't seem to build the query correctly.