Insert Query - Basic Question

Apr 28, 2006

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,

Regards

View 1 Replies


ADVERTISEMENT

Basic Insert And Query

Nov 20, 2007

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);

sqlCommand.Parameters.Add(SevParam);
sqlCommand.Parameters.Add(MsgParam);

try
{
pConn.Open();
resultSet = sqlCommand.ExecuteResultSet(ResultSetOptions.None);
}
finally
{
pConn.Close();
}
return !(resultSet == null);


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.

Thanks!
=Spencer Whitman

View 1 Replies View Related

Trouble Doing Basic Insert Into Sql Db

Jul 18, 2006

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.

here is the code for the testInsert.aspx page:

<%@ Page Explicit="True" Language="VB" Debug="True" %>
<%@ Import Namespace="System.Data"  %>
<%@ Import Namespace="System.Data.SqlClient"  %>
<html>
<body vlink="red">
<h1>title and category</h1>

<form id="Form1" runat="server">

<h2>Enter title and category</h2>

<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs)
   
        DetailsView1.ChangeMode(DetailsViewMode.Insert)
End Sub

Protected Sub DetailsView1_ItemInserted( _
    ByVal sender As Object, ByVal e As _
    System.Web.UI.WebControls.DetailsViewInsertedEventArgs)
   
        Response.Redirect("../Pages/Home.aspx")
End Sub

Protected Sub Detailsview1_ItemCommand( _
    ByVal sender As Object, ByVal e As _
    System.Web.UI.WebControls.DetailsViewCommandEventArgs)
   
        If e.commandName = "Cancel" Then
            Response.Redirect("../Pages/Home.aspx")
        End If
End Sub
</script>
Enter your e-mail address
<br />

<asp:DetailsView ID="DetailsView1" runat="server"
Height="50px" Width="100%" AutoGenerateRows="False"
DataKeyNames="AdNum" DataSourceID="SqlDataSource1"
CellPadding="4" ForeColor="#333333" GridLines="None"
OnItemInserted="DetailsView1_ItemInserted"
OnItemCommand="DetailsView1_ItemCommand">

    <Fields>
        <asp:BoundField DataField="Title"
            HeaderText="Title"
                SortExpression="Title" />
        <asp:BoundField DataField="Category"
            HeaderText="Category"
            SortExpression="Category" />
        <asp:Commandfield ButtonType="Button"
            ShowInsertButton="True" />
    </Fields>
   
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
   
    <FieldHeaderStyle BackColor="#FFFF99" Font-Bold="True" />
   
</asp:DetailsView>

&nbsp;

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString=
"<%$ ConnectionStrings:ASPNETDBConnectionString3 %>"
InsertCommand="INSERT INTO newInsert (Title, Category) Values(?, ?)"
ProviderName=
"<%$ ConnectionStrings:ASPNETDBConnectionString3.ProviderName %>"
SelectCommand="SELECT Title, Category FROM newInsert" >

    <InsertParameters>
        <asp:Parameter Name="Title" Type="String" />
        <asp:Parameter Name="Category" Type="String" />
    </InsertParameters>
</asp:SqlDataSource>

</form>
</body>
</html>


and here is the portion of my web.config file that references the connectionstrings:

<connectionstrings>
<add name="ASPNETDBConnectionString3" connectionString="Data
Source=.SQLEXPRESS;AttachDbFilename=&quot;C:Documents and
SettingsJordan MikoMy DocumentsVisual Studio
2005WebSitesWebSite29App_DataASPNETDB.MDF&quot;;Integrated
Security=True;Connect Timeout=30;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

The connectionstring, table, and rows are all correctly spelled
please let me know what i am doing wrong or an easier way to do it


jordan

View 2 Replies View Related

Basic SQL INSERT Question

May 7, 2008

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!
 
 

View 11 Replies View Related

INSERT Problems - Basic!

Jul 26, 2006

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

strSQL = "INSERT INTO Member(FirstName)" & _
"Values('" & request("FirstName") & "')"

conn.execute(strSQL)

Response.Redirect "success.asp"

Else
response.redirect("register.asp?signuperror=" & " UserName"& " " & "<b>" & username & "</b>" & " already exists, Please try another username" )

End If

rs.Close
Set rs=Nothing
rst.Close
Set rst=Nothing
conn.Close
Set conn=Nothing
%>

The page generates this error:
Invalid object name 'Member'.

/members/regchk.asp, line 16

which makes me think that it doesn't even recognize the table as existing?? Any ideas what I'm doing wrong? It's driving me crazy..


Please help! and thank you in advance!

View 5 Replies View Related

Basic Insert Question

Aug 30, 2007

Hi,

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.

Here's the query:

INSERT INTO `flexing_phs`.`flexing_stock_header` (
`record` ,
`week_starting` ,
`supplier_account` ,
`advice_no` ,
`date_recvd` ,
`firm_or_commission` ,
`comm_percent` ,
`invoice_number` ,
`invoice_date` ,
`invoice_status` ,
`tot_value_cost` ,
`tot_value_sold` ,
`tot_commission` ,
`tot_profit` ,
`carriage` ,
`comments` ,
`user_name`
)
VALUES (
NULL ,
'$saveGoodsInDate',
'$saveAccountNumber' ,
'$saveAdviceNote',
'$saveDateReceived' ,
'$saveFirmComm',
'$saveCommPercent',
NULL ,
NULL ,
NULL ,
'$saveTotalCost' ,
NULL ,
NULL ,
NULL ,
NULL ,
NULL ,
'$saveUserName'
);

View 3 Replies View Related

SQLCeconnection On Visual Basic And Insert Data On A Listbox

Nov 13, 2007



Hi

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:


Dim conn As New SqlCeConnection()

Dim Recordset As SqlCeDataAdapter

Dim SQL As String

Dim ds As New DataSet

conn.ConnectionString = _

"Data Source = '.BDDclimatologicos.sdf';"

conn.Open()

SQL = "select [Provincia] from ZonasClimaticas"

Recordset = New SqlCeDataAdapter(SQL, conn)

Recordset.Fill(ds, "ZonasClimaticas")

lstboxProvincias.DataSource = ds.Tables("ZonasClimaticas").DefaultView


I have Dcilmatologicos.sdf on a folder named BD next to the folder of the executable, I donīt know what happends.

My database has one table "ZonasClimaticas" and a column named "Provincia" on that, my other question is:

Is this the right code to show that column on a listbox?

Thank you very much!

View 4 Replies View Related

Reporting Services :: Insert Basic Sparkline For Multiple Columns?

Aug 19, 2015

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).

View 12 Replies View Related

A Basic Sql Query Problem

Jul 14, 2007

 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.

View 3 Replies View Related

Basic Query Help - Revisited

Jul 14, 2001

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....

table2 log
id ondate
02anandt 07/01/01
02anandt 07/03/01
02anandt 07/03/01
01smithj 07/03/01
03burtot 07/05/01
01smithj 07/05/01
03burtot 07/05/01
etc.....

View 1 Replies View Related

Basic COUNT Query

Aug 7, 2013

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

View 5 Replies View Related

What Looks Like A Basic SQL Query Still Not Resolved

Nov 23, 2005

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

View 6 Replies View Related

Basic Sql Query Needed

Jul 20, 2005

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

View 2 Replies View Related

Converting Basic EffDt Query To SQL-92 Standard

Jan 28, 2005

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()
)

View 1 Replies View Related

[absolute Beginner] Help For SQL Basic Query Exercise

Apr 29, 2008

hi

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


====================================================

Query Results needed:


ingredient pizza amount
------------------------------
anchovies napolitana 100
bacon special 25
cabanossi cabanossi 150
capsicum mexicano 75
capsicum siciliano 75
cheese margarita 120
chilli mexicano 25
egg special 25
garlic garlic 25
ham ham 150
mushroom mushroom 100
olives napolitana 75
onion mexicano 75
peas vegetarian 50
pepperoni americano 75
pineapple hawaiian 100
salami americano 120
seafood seafood 200
spice mexicano 20
tomato vegetarian 50

=============================================

Thanks

View 10 Replies View Related

Basic SQL Query (Select Records Added Today)

Aug 19, 2005

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

View 9 Replies View Related

Basic Query: Alternatives To 'Group By' For NText Column

Apr 19, 2004

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

View 2 Replies View Related

Ssis Creating A Basic Package Tutorial - Not A Query

Jun 13, 2006

In the tutorial Creating a Basic Package Using a Wizard > Lesson 1: Creating the Basic Package >

says to use the following sql statement on the query page:

SELECT * FROM [Customers$] WHERE NumberCarsOwned > 0

When I paste the query in I get the message :

This SQL statement is not a query.

Does anyone have any suggestions?  The input and output are set up correctly and I have the sample excel file Customers.xls. 

I am new to all this, is there some setting I need to change for the tutorial to work or..?

FYI I have installed Sql 2005, Sp1.

 

View 4 Replies View Related

Trouble With Basic Table To Table Insert

Nov 26, 2001

I'm a horrible noob everyone, so my apologies come up front.

I know Oracle allows me to just do an

INSERT INTO table
SELECT column1, column2
FROM table2

But I cannot get this to work in MS SQL 2000. (See question #3)



Here's my script that I'm trying to execute from Enterprise Manager:

From this table:

CREATE TABLE ISIS_DATA
(ISIS_STATUS_ID VARCHAR(15) CONSTRAINT ISIS_DATA_ISIS_ID_PK PRIMARY KEY,
ISIS_NAME VARCHAR(50),
ISIS_CLASS_EXPIR_DAT VARCHAR(20),
ISIS_SEX_BD_CAT_SCHL VARCHAR(20))

Where this is a sample row of data:

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))


Using this script so far:


INSERT INTO ISIS_DATA_PREP
SELECT B.STATUS, B.STUDENT_ID, B.LAST_NAME, B.FIRST_NAME, B.MID_INIT,
B.CLASS, B.EXPIR_DATE,
B.SEX, B.BIRTHDAY, B.CAT, B.SCHOOL, A.ISIS_STATUS_ID
FROM ISIS_DATA A,
(SELECT SUBSTRING(ISIS_STATUS_ID, 1, 1) STATUS, SUBSTRING(ISIS_STATUS_ID, 2, 9) STUDENT_ID,
ISIS_NAME LAST_NAME, SUBSTRING(ISIS_NAME, 5, 1) FIRST_NAME, SUBSTRING(ISIS_NAME, 5, 1) MID_INIT,
SUBSTRING(ISIS_CLASS_EXPIR_DAT, 1, 1) CLASS, SUBSTRING(ISIS_CLASS_EXPIR_DAT, 2, 8) EXPIR_DATE,
SUBSTRING(ISIS_SEX_BD_CAT_SCHL, 1,1) SEX, SUBSTRING(ISIS_SEX_BD_CAT_SCHL, 2, 8) BIRTHDAY,
SUBSTRING(ISIS_SEX_BD_CAT_SCHL, 10, 1) CAT, SUBSTRING(ISIS_SEX_BD_CAT_SCHL, 11, 2) SCHOOL,
ISIS_STATUS_ID
FROM ISIS_DATA) B
WHERE A.ISIS_STATUS_ID = B.ISIS_STATUS_ID


I keep getting this error:


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.

Lance

View 2 Replies View Related

Wants To Insert Into Multiple Table By A Single Insert Query

Apr 11, 2008

Hi,ALL
I wants to insert data into multiple table within a single insert query
Thanks

View 3 Replies View Related

Can I Roll Back Certain Query(insert/update) Execution In One Page If Query (insert/update) In Other Page Execution Fails In Asp.net

Mar 1, 2007

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

View 2 Replies View Related

Help With Insert SQL Query

Jan 21, 2007

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?

View 4 Replies View Related

Insert Query ?

Mar 15, 2007

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 ....
 

View 1 Replies View Related

INSERT INTO Query Help...

Jan 10, 2008

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!

View 5 Replies View Related

Insert Query

Apr 3, 2008

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 

View 3 Replies View Related

SQL Insert Query

Jun 14, 2008

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

View 2 Replies View Related

Is This 'Insert Into' Query Possible?

Dec 1, 2005

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?

View 1 Replies View Related

Insert From Query

Dec 3, 2004

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

View 5 Replies View Related

Insert Query

Apr 28, 2008

Hi All,

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.

Any help or advice would be greatly appreciated.

Cheers,
Jon

View 11 Replies View Related

Best Way To Right This Insert Query

May 1, 2008

Hi. I have 2 tables, this structure (basically);

Code Title
1 AAAAA
2 BBBBB
3 CCCCC
4 DDDDD

Code Title
1 AAAAA
2 BBBBB

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.

Thanks so much for your help in advance.

View 3 Replies View Related

INSERT QUERY

Sep 1, 2005

Hello friends!

I want to know weather we can insert more than 1 records from a single INSERT query in query analyzer?

If yes please tell me how to..

Thankyou.

View 1 Replies View Related

Sub Query Insert

Sep 20, 2005

use Dacari
go

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

CREATE PROCEDURE dbo.InsITRRComments

@CommentId int,
@DacType varchar(25),
@DacTypeId int,
@TypeOfComment varchar(50),
@Comments varchar(4000),
@RiskId_External_ID varchar(16),
@UserId varchar(25),
@FullUserName varchar(50),
@AmendedDateTime datetime,
@ProcessedFlag char(1)

AS
BEGIN
/*************************************************************************
*
* Name: InsITRRComments
*
* Description: Insert new Term Type item.
*
* Inputs:
* @CommentId
* @DacType
* @DacTypeId
* @TypeOfComment
* @Comments
* @RiskId_External_ID
* @UserId
* @FullUserName
* @AmendedDateTime
* @ProcessedFlag
*
* Outputs: None
*
*
* Notes:
*
* History:
* Date Author Changes
* ------------------------ -------------------------------------------
* 16 Sept 05xxxxxxxxxxxxxx Original
*************************************************************************/

---------------------------------------------------------------------------


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

View 9 Replies View Related

Insert From Query

Feb 8, 2006

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.

View 15 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved