Insert Query And Number Of Fields

Apr 18, 2008

I've found out how to to the Insert into my table (col1, col2) Select (col1, col2...) from othertable where regId= @regId in my earlier question but do i have to name every column as i have about 80 in my table. Can't I use an asterisk or something....

View 4 Replies


ADVERTISEMENT

Need Help Using Bulk Insert From A CSV With A Variable Number Of Fields

Dec 6, 2007

Hi folks....

I am able to import a CSV file into a temporary table as long as I know the number of fields in the CSV file. Here is what I would like to do:

I would like to have a CSV file which has UP to 6 entries per row. I would like to insert each row into a table; if the there three fields, then I want to insert them into the first three columns to the temporary table. If there are four, then insert into the first four fields. Is this possible?

Does anyone have any suggestions?

Thanks!

Forch

View 4 Replies View Related

SQL Server 2012 :: Query To Get Count Of All Fields Named LX Where X Is A Number

Jan 29, 2015

For example in a table with this fields "field1, L1,L3,L100" field2 the count is 3

it would be better to match a number into the like but i thinks it cannot be done in the like so i've to add another condition to ensure all the text after L is a number.

is this the best way to do it?

Select count(*) from Information_Schema.Columns Where Table_Name = @Table
AND column_name like 'L%' and ISNUMERIC(SUBSTRING(column_name,2, len(column_name)-1))=1

View 6 Replies View Related

Insert Query Fails (if Form Fields Left Empty)

Aug 13, 2007

Dear All,
I have created a table in my SQL server database, the problem i am facing is my insert query fails if i leave any form field empty (leave it blank). On my back-end table, only one field is mandatory, and others have been set with the constraint "allow null".
As per our business requirement, except one value is complusory while others are optional. If I enter all values in the form it works perfectly fine. Can you see in the code below - where am i possibly going wrong ?
<script language="VB" runat="server" >      Sub Page_Load(Src As Object, e As EventArgs)                      If Page.IsPostBack Then                        Dim ConLath As SqlConnection            Dim comLath As SqlCommand            Dim insertcmd                        conLath = New SqlConnection("Data Source=SQLas;Initial Catalog=settle;User ID=sa;Password=password")            ConLath.Open()            insertcmd = "Insert into His_set values (@t_d,@s_p,@p_s,@v_oq,@i_oq,@v_qn,@i_qn,@v_qw,@i_qw)"                        comLath = New SqlCommand(insertcmd, ConLath)                                    comLath.Parameters.Add(New SqlParameter("@t_d", SqlDbType.DateTime, 12))            comLath.Parameters("@t_d").Value = trade_date.Text            comLath.Parameters.Add(New SqlParameter("@s_p", SqlDbType.Decimal, 8))            comLath.Parameters("@s_p").Value = sett_price.Text            comLath.Parameters.Add(New SqlParameter("@p_s", SqlDbType.Decimal, 8))            comLath.Parameters("@p_s").Value = post_close.Text            comLath.Parameters.Add(New SqlParameter("@v_oq", SqlDbType.Int, 8))            comLath.Parameters("@v_oq").Value = vol_oq.Text            comLath.Parameters.Add(New SqlParameter("@i_oq", SqlDbType.Int, 8))            comLath.Parameters("@i_oq").Value = oi_oq.Text            comLath.Parameters.Add(New SqlParameter("@v_qn", SqlDbType.Int, 8))            comLath.Parameters("@v_qn").Value = vol_qn.Text            comLath.Parameters.Add(New SqlParameter("@v_qw", SqlDbType.Int, 8))            comLath.Parameters("@v_qw").Value = vol_qw.Text            comLath.Parameters.Add(New SqlParameter("@i_qn", SqlDbType.Int, 8))            comLath.Parameters("@i_qn").Value = oi_qn.Text            comLath.Parameters.Add(New SqlParameter("@i_qw", SqlDbType.Int, 8))            comLath.Parameters("@i_qw").Value = oi_qw.Text
                        Try                comLath.ExecuteNonQuery()                            Catch ex As SqlException                If ex.Number = 2627 Then                    Message.InnerHtml = "ERROR: A record already exists with " _                       & "the same primary key"                Else                    Message.InnerHtml = "ERROR: Could not add record, please " _                       & "ensure the fields are correctly filled out"                    Message.Style("color") = "red"                End If            End Try
            comLath.Dispose()            ConLath.Close()                                                        End If   End Sub
</script>
 

View 6 Replies View Related

Trouble With An ASync Query To Insert A Record And Return The Auto Number Field.

Aug 31, 2007

I get this error when I look at the state of my SQLresults object. Have I coded something wrong?Item = In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.  conn.Open()
Dim strSql As String

strSql = "INSERT INTO contacts (companyId, sourceId, firstName, lastName, middleName, birthday, dateCreated)" _
& "VALUES ('" & companyId & "', '" & sourceId & "', '" & firstName & "', '" & lastName & "', '" & middleName & "', '" & birthday & "', '" & now & "') SELECT @@IDENTITY AS 'contactId'"

Dim objCmd As SqlCommand
objCmd = New SqlCommand(strSql, conn)

Dim aSyncResult As IAsyncResult = objCmd.BeginExecuteReader()

If aSyncResult.AsyncWaitHandle.WaitOne() = True Then


Dim sqlResults As SqlClient.SqlDataReader

sqlResults = objCmd.EndExecuteReader(aSyncResult)

Dim cid As Integer



cid = sqlResults.Item("contactId")
Me.id = cid
conn.Close()
Return cid
Else
Return "failed"


End If  

View 3 Replies View Related

Strange Problem: SQL Insert Statement Does Not Insert All The Fields Into Table From Asp.net C# Webpage

Apr 21, 2008

An insert statement was not inserting all the data into a table. Found it very strange as the other fields in the row were inserted. I ran SQL profiler and found that sql statement had all the fields in the insert statement but some of the fields were not inserted. Below is the sql statement which is created dyanmically by a asp.net C# class. The columns which are not inserted are 'totaltax' and 'totalamount' ...while the 'shipto_name' etc...were inserted.there were not errors thrown. The sql from the code cannot be shown here as it is dynamically built referencing C# class files.It works fine on another test database which uses the same dlls. The only difference i found was the difference in date formats..@totalamount=1625.62,@totaltax=125.62are not inserted into the database.Below is the statement copied from SQL profiler.exec sp_executesql N'INSERT INTO salesorder(billto_city, billto_country, billto_line1, billto_line2, billto_name,billto_postalcode, billto_stateorprovince, billto_telephone, contactid, CreatedOn, customerid, customeridtype,DeletionStateCode, discountamount, discountpercentage, ModifiedOn, name, ordernumber,pricelevelid, salesorderId, shipto_city, shipto_country,shipto_line1, shipto_line2, shipto_name, shipto_postalcode, shipto_stateorprovince,shipto_telephone, StateCode, submitdate, totalamount,totallineitemamount, totaltax ) VALUES(@billto_city, @billto_country, @billto_line1, @billto_line2,@billto_name, @billto_postalcode, @billto_stateorprovince, @billto_telephone, @contactid, @CreatedOn, @customerid,@customeridtype, @DeletionStateCode, @discountamount,@discountpercentage, @ModifiedOn, @name, @ordernumber, @pricelevelid, @salesorderId,@shipto_city, @shipto_country, @shipto_line1, @shipto_line2,@shipto_name, @shipto_postalcode, @shipto_stateorprovince, @shipto_telephone,@StateCode, @submitdate, @totalamount, @totallineitemamount, @totaltax)',N'@billto_city nvarchar(8),@billto_country nvarchar(13),@billto_line1 nvarchar(3),@billto_line2 nvarchar(4),@billto_name nvarchar(15),@billto_postalcode nvarchar(5),@billto_stateorprovince nvarchar(8),@billto_telephone nvarchar(3),@contactid uniqueidentifier,@CreatedOn datetime,@customerid uniqueidentifier,@customeridtype int,@DeletionStateCode int,@discountamount decimal(1,0),@discountpercentage decimal(1,0),@ModifiedOn datetime,@name nvarchar(33),@ordernumber nvarchar(18),@pricelevelid uniqueidentifier,@salesorderId uniqueidentifier,@shipto_city nvarchar(8),@shipto_country nvarchar(13),@shipto_line1 nvarchar(3),@shipto_line2 nvarchar(4),@shipto_name nvarchar(15),@shipto_postalcode nvarchar(5),@shipto_stateorprovince nvarchar(8),@shipto_telephone nvarchar(3),@StateCode int,@submitdate datetime,@totalamount decimal(6,2),@totallineitemamount decimal(6,2),@totaltax decimal(5,2)',@billto_city=N'New York',@billto_country=N'United States',@billto_line1=N'454',@billto_line2=N'Road',@billto_name=N'Hillary Clinton',@billto_postalcode=N'10001',@billto_stateorprovince=N'New York',@billto_telephone=N'124',@contactid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@CreatedOn=''2008-04-18 13:37:12:013'',@customerid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@customeridtype=2,@DeletionStateCode=0,@discountamount=0,@discountpercentage=0,@ModifiedOn=''2008-04-18 13:37:12:013'',@name=N'E-Commerce Order (Before billing)',@ordernumber=N'BRKV-CC-OKRW5764YS',@pricelevelid='B74DB28B-AA8F-DC11-B289-000423B63B71',@salesorderId='9CD0E11A-5A6D-4584-BC3E-4292EBA6ED24',@shipto_city=N'New York',@shipto_country=N'United States',@shipto_line1=N'454',@shipto_line2=N'Road',@shipto_name=N'Hillary Clinton',@shipto_postalcode=N'10001',@shipto_stateorprovince=N'New York',@shipto_telephone=N'124',@StateCode=0,@submitdate=''2008-04-18 14:37:10:140'',@totalamount=1625.62,@totallineitemamount=1500.00,@totaltax=125.62
 
thanks

View 7 Replies View Related

How To Select Max Value Among A Number Of Fields For Every Row?

Jan 2, 2004

Hi,

I have a fairly basic query I want to make but I'm struggling on figuring out how to do it. Let's say I have some fields (e.g. Value1, Value2, Value3, etc). I simply want to do a Select statement that returns the highest value among those fields for every row in my db.

At first I thought of the built in Max function until I realized that is for within a column only.

Any help would be appreciated, thank you.

View 4 Replies View Related

Number Of Fields In A Table?

Jan 4, 2004

My users login from the tbl_users table.

I would like to store all information on them in this table but that amounts to quite a lot of fields (about 50) and some of these will store a lot of HTML text in them.

Is it best to split the table up for performance reasons or will it make little difference?

Thanks,
JB

View 4 Replies View Related

Number Of Fields In A Table

Mar 6, 2000

I'm new to SQL Server 7. Is there a limit to the number of fields that a table can have?

View 1 Replies View Related

Increment Number On Fields With Same Value

Dec 2, 2013

I have a Column named 'Series' and a column named 'Linenumber'. They look like this:

Series Linenumber
234 NULL
234 NULL
235 NULL
235 NULL
234 NULL
234 NULL
235 NULL
235 NULL
236 NULL
236 NULL
236 NULL

And I want to run a query and make it look like this:

Series Linenumber
234 1
234 2
235 1
235 2
234 3
234 4
235 3
235 4
236 1
236 2
236 3

So basically I want Linenumber to be an increment column but to increment seperately for each value of Series. RDBMS is Microsoft SQL Server 2008.

View 4 Replies View Related

How To Deal With No Fix Number Of Fields?

Oct 19, 2007

hi,

i'm wondering if there's a possibility for me to insert values into a table without knowing fix number of fields? in other words, i won't know how many fields i have in a single table until users enter data.

any suggestions or recommendations are welcome. thanks in advance.

View 12 Replies View Related

Number Of Fields In A Table

Mar 19, 2007

I am working on a project which requires having a form that must be filled by the user. The number of the fields on this form is arround 150. Is it a good idea to have a database table with 150 fields (columns)? If its not what would be a better approach for this case? Handling this many fields on a windows form is another issue but first I would like to know about how to deal with the data storage.

Any help is appreciated.

Thanks

View 9 Replies View Related

OPENROWSET (INSERT) Insert Error: Column Name Or Number Of Supplied Values Does Not Match Table Definition.

Mar 24, 2008

Is there a way to avoid entering column names in the excel template for me to create an excel file froma  dynamic excel using openrowset.
I have teh following code but it works fien when column names are given ahead of time.
If I remove the column names from the template and just to Select * from the table and Select * from sheet1 then it tells me that column names donot match.
 Server: Msg 213, Level 16, State 5, Line 1Insert Error: Column name or number of supplied values does not match table definition.
here is my code...
SET @sql1='select * from table1'SET @sql2='select * from table2'  
IF @File_Name = ''      Select @fn = 'C:Test1.xls'     ELSE      Select @fn = 'C:' + @File_Name + '.xls'        -- FileCopy command string formation     SELECT @Cmd = 'Copy C:TestTemplate1.xls ' + @fn     
-- FielCopy command execution through Shell Command     EXEC MASTER..XP_CMDSHELL @cmd, NO_OUTPUT        -- Mentioning the OLEDB Rpovider and excel destination filename     set @provider = 'Microsoft.Jet.OLEDB.4.0'     set @ExcelString = 'Excel 8.0;HDR=yes;Database=' + @fn   
exec('insert into OPENrowset(''' + @provider + ''',''' + @ExcelString + ''',''SELECT *     FROM [Sheet1$]'')      '+ @sql1 + '')         exec('insert into OPENrowset(''' + @provider + ''',''' + @ExcelString + ''',''SELECT *     FROM [Sheet2$]'')      '+ @sql2 + ' ')   
 
 

View 4 Replies View Related

Re-populate A Unique Number Into Multiple Fields

Oct 14, 2004

What I need to do is re-populate a unique number into multiple fields,

Let me explain, An employee can appear in the first table only once but can be in the second table multiple times with multiple employee numbers .There is a field called TFN that is unique and we are using it to create a unique id called KRid so what I have done is created 2 tables namely TEST_TBL and TEST2_TBL . In TEST_TBL I am populating a KRid with a unique no being produced by the TFN field only once i.e 12345 being the resulting unique id number. If an employee has 2 employee numbers i.e empno 1 and empno 1000,only employee no 1 will have the unique KRid created but nothing for 1000 because the record already exists , so what has me stumped is that the TFN for employee empno 1 and the TFN for empno 1000 are the same. How do I get the KRid (12345 from empno 1) to populate empno 1000 in TEST2_TBL , The second table has all records in so I can group the second table by TFN id but how do I populate employee 1000 in the second table with the KRid 12345.


Please help!!!!! Below are how the tables are set up and an example of the result.

TABLE 1

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TEST_TBL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TEST_TBL]
GO

CREATE TABLE [dbo].[TEST_TBL] (
[Empl_Num] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Surname] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[First_Name] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Mid_Name] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Hours_Day] [numeric](18, 2) NULL ,
[Hours_Wk] [numeric](18, 2) NULL ,
[KR_ID] [bigint] IDENTITY (1, 1) NOT NULL ,
[TFN] [char] (32) COLLATE Latin1_General_CI_AS NULL ,
[Date_Term] [datetime] NULL ,
[Empl_Type] [int] NULL ,
[Cost_Centre] [char] (32) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Empl_Status] [int] NULL
) ON [PRIMARY]
GO

TABLE 2

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TEST2_TBL]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TEST2_TBL]
GO

CREATE TABLE [dbo].[TEST2_TBL] (
[EmpNumber] [char] (32) COLLATE Latin1_General_CI_AS NULL ,
[TFN] [char] (32) COLLATE Latin1_General_CI_AS NULL ,
[KR_ID] [char] (10) COLLATE Latin1_General_CI_AS NULL ,
[EmpStatus] [int] NULL ,
[EmpType] [int] NULL ,
[CommonName] [char] (32) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]
GO

Query goes as follows for table 1:

SELECT NPE000.EmpNumber, NPET00.RecordStatus, NPE000.KR_ID, NPE000.Surname, NPE000.FirstName, NPE000.SecondName, NPE000.Class, NPE000.DateEmployed, NPE000.DateOfBirth, NPE000.HoursPerDay, NPE000.HoursPerWeek, NPE000.PassportNo, NPE000.AwardCode, NPE000.EmailPayslipTo, NPE000.Location, NPE000.Grade, NPE000.DateTerminated, NPE000.EmploymentType, NPE000.DistCode, NPE000.EmpStatus, NPET00.TaxRefNo FROM NPE000 NPE000, NPET00 NPET00 WHERE NPET00.RecordStatus = 0 and NPET00.TaxRefNo <> ' 111111111' and NPET00.TaxRefNo <> ' 000000000' AND LENGTH(NPET00.TaxRefNo) >= 9 AND LENGTH(NPE000.KR_ID) >= 0 AND NPE000.EmpNumber = NPET00.EmpNumber


Query goes as follows for table 2:

SELECT NPE000.EmpNumber, NPE000.FirstName, NPE000.Surname, NPE000.Class, NPE000.Location, NPE000.EmploymentType, NPE000.EmpStatus, NPET00.TaxRefNo, NPE000.Paypoint, NPE000.KR_ID, FROM NPE000, NPET00 WHERE Recordstatus = 0 and (EmploymentType = 1 AND EmpStatus = 1 AND NPE000.EmpNumber = NPET00.EmpNumber


From this you can see that in table 1 it will only create 1 KR_ID for only one employee number but in table 2 I am bringing through all employee records. In table 2 I can group by NPET00.TaxRefNo which will bring all NPET00.TaxRefNo's togeather. From that I would like to populate the other employee numbers with the unique KR_ID.

Example:Table 1

000001,Jackson,James,Sam,7.6,38,12345,475431212


Example:Table 2

000001,Jackson,James,Sam,7.6,38,12345,475431212
001000,Jackson,James,Sam,7.6,38,,475431212

I hope this helps

Thanks in advance

View 10 Replies View Related

T-SQL (SS2K8) :: Varying Calculation For Fixed Number Of Fields

Aug 19, 2014

I'm writing a query that will be used in Jasper Ireports, but prefer to have the values done ahead of time using SQL rather than relying on the report to do the lifting.The fields are pretty straight forward, only the display is where I have a question.

Fields Used: PERIOD ('MON-yyyy') and VALUE

The results must start with the CURRENT PERIOD (AUG-2014) in one column and the VALUE for the current period multiplied by 1/12 (VALUE*(1/12)).The next column should return the VALUE for CURRENT PERIOD - 1 (JUL-2014) and multiply by 2/12 (VALUE*(2/12))

This should continue for the last 11 months and would end with OCT-2013 with the value being multiplied (VALUE*(11/12)).Is the easiest solution to this a CASE statement looking at PERIOD then PERIOD minus one month, minus two months...etc?

View 1 Replies View Related

Return Number Of Days By Year From Date Fields

Dec 3, 2013

I need to associate aggregate gross_revenue with calendar year, but do not have a date field that reflects payment dates, just contract periods a start_date and an end_date. The contract periods are typically 1 or 2 years and can start at any time I.e start_date 6/1/2012, end date 5/31/13. I think by finding the number of days that fall in each calendar year and storing in a temp table, I can create a simple formula to associate revenue to each year.

View 2 Replies View Related

Processing CSV Flat Files With Records Of Number Of Fields

Mar 10, 2008

Hello I have some flat files that contain CSV records with different number of fields but the first 4 fields of each record type are the same of each re. eg there would be an entry of one record that has eight fields and another that has 6 fields. Which of the items in the toolbox can i use to filter the records based on the entry in the first 4 fields so i can process the filtered records.

Thank you
Kenalex

View 5 Replies View Related

SSIS - How To Deal With A Csv File That Contains Multiple Records With A Differing Number Of Fields

Apr 20, 2007

what is the best way to uses ssis to deal with a CSV file that contains a number of records that contain a different number of fields ?

I could just load as a single column delimited by <CRLF> but then I would have to write the code to parse the line, effectively detokenising the columns myself but if that is the case then why uses ssis at all ?

View 13 Replies View Related

Contact Form - Variable Number Of Input Fields, Store Data As Xml String ?

Jul 13, 2007

Im trying to determine the best way to store data gathered from a form that a user will fill out online.  The form is dynamic and is customized at run time based on group-specific criteria.  The end result is a form that might have 3 extra text boxes, 2 extra sets of radio buttons and a freeform textbox, whereas for another group, there might be a slightly different set of input fields.   Now comes the issue of storing this data.  Since the fields can be somewhat dynamic, it could get tricky to define table columns for each possible input field.  So Im considering storing the data as xml.  Has anyone else had to build custom forms and ended up storing the data as xml ?

View 2 Replies View Related

IDs For Insert And Modified Fields

Jan 21, 2015

if you all add ID's with your Inserts and Modified (Date) fields. Such as 1 would indicate if the record was inserted manually, whereas 2 might indicate it was update or inserted by a web application.

View 2 Replies View Related

Insert Does Not Map To Correct Fields

Feb 4, 2008

I have created 2 tables and populated them with data. When doing an inert into #JoblistTable from #EquentialJobListTable, fields are not mapped correctly. Example: qty_delivered in #JobListTable is filled with data from qty_received from #EquetialJobListTable?


CREATE TABLE#JobListTable
(
job_date datetime,
job_number char(15),
cost_code char(15),
qty_delivered decimal(8,2),
qty_received decimal(8,2),
qty_used decimal(8,2),
qty_wasted decimal(8,2),
plant_id char(10)
)
Fill table.........

CREATE TABLE#EquentialJobListTable
(
job_date datetime,
job_number char(15),
cost_code char(15),
qty_received decimal(8,2),
qty_used decimal(8,2),
qty_wasted decimal(8,2),
plant_id char(10)
)

Fill table .......


INSERT#JobListTable
(
job_date,
job_number,
cost_code,
qty_delivered,
qty_received,
qty_used,
qty_wasted,
plant_id
)
SELECTt2.job_date,
t2.job_number,
t2.cost_code,
t2.qty_received,
t2.qty_used,
t2.qty_wasted,
t2.plant_id,
case
when t2.plant_id = 320 then 'RGFP'
when t2.plant_id = 300 then 'RGWP'
when t2.plant_id = 600 then 'RGDF'
when t2.plant_id = 330 then 'RGGT'
when t2.plant_id = 350 then 'RGWG'
when t2.plant_id = 340 then 'RGDB'
when t2.plant_id = 610 then 'RGMI'
when t2.plant_id = 110 then 'SBGB2'
end
FROM#EquentialJobListTable AS t2
LEFT JOIN#JobListTable AS t1 ON
t1.job_date = t2.job_date
AND t1.job_number = t2.job_number
AND t1.cost_code = t2.cost_code
WHEREt1.job_date IS NULL

View 2 Replies View Related

How To Query A Number (street Number)...

Jul 30, 2007

I have a table that has a street number field.
if the user types in a street number of '2' i would like to return all street numbers the begin with 2 (2,20,21, 200, 201,205,2009,...)
how can this be done.

View 10 Replies View Related

BULK INSERT And Text Fields

May 30, 2004

Hi,

I am trying to do a bulk insert using a text file that is comma delimited.

In the text file there are fields which are surrounded by quotes and contain commas; these commans should not be considered delimiters.

Is there a way to tell the BULK INSERT statement not to treat these as delimiters?

thanks,

sivilian

View 2 Replies View Related

Insert Values Of All The Fields Into Variable?

Aug 7, 2014

I need to create a stored procedures, this procedure will receive two parameters:

@TableName

@KeyField

I need to storage into a variable the values of ALL THE FIELDS separeted by |

For example if my table is Customers

CustomerID CustomerName City

111 Adventure Boston

222 Pubs NY

And I execute EXEC mysp 'Customers',111

I need a return value like this

@ReturnValue = 111|Adventure|Boston

I create something like this

CREATE PROCEDURE my sp
@table varchar
@key numeric
AS
@field varchar(40),
@object int
Select @object = object_id from systables where name =@table

--The instructions to create a cursor

WHILE (@@FETCH_STATUS = 0 )
Select @object = name from sys.columns where object_id = @object

--The instructions to close and deallocate the cursor

I have alredy to save the value using the EXEC command but is not working; something like

@String = Select @object from @table where CustomerID = @keyValue

View 1 Replies View Related

Need Help With Insert Statement On Table With Several Non-null Fields

Apr 30, 2007

On my aspx page I have a basic sqldatasource and gridview - both were set up using the wizards. The SQL Server 2000 database table that the sqldatasource is querying has some fields in it that are set to not allow nulls, however, the gridview control is not displaying all of the fields in the table - including some of the non-null fields.
My problem is, when I run an insert on the table from my aspx page, I get an error that says: "Cannot insert the value NULL into column 'ColumnName', table 'TableName'; column does not allow nulls. INSERT fails. The statement has been terminated."
The 'ColumnName', as you may have guessed, is one of the aforementioned columns that doesn't allow nulls, but isn't in the GridView.
How can I do an insert on this table without messing with the non-null fields. Those fields are relevant to the purposes of the gridview, so I don't want to display them, let alone allow editing of them.
Any suggestions on my options would be greatly appreciated!
Thanks
Capella07

View 2 Replies View Related

How Do I Insert Datagridr Checkbox Into SQL Bit Fields Using A SqlDataSource

Apr 13, 2006

Dim strStatus As String
Dim strGroup As String
Dim strLicense As String = dtgPhysician.DataKeys(e.Item.ItemIndex)
Dim strUpdateStatus As String
Dim strUpdateGroup As String
Dim strName As String
Dim strDate As String
Dim strSubject As String
Dim blPDA As Boolean
Dim strPDA As Byte
strStatus = CType(e.Item.FindControl("lstStatus"), DropDownList).SelectedItem.Text
strGroup = CType(e.Item.FindControl("txtGroup"), TextBox).Text
strName = e.Item.Cells(1).Text.Trim
strDate = CType(e.Item.FindControl("txtDate"), TextBox).Text
strSubject = CType(e.Item.FindControl("dpTraining"), DropDownList).SelectedItem.Text
blPDA = CType(e.Item.FindControl("ckPDA"), CheckBox).Checked
strPDA = Convert.ToString(blPDA)

strUpdateStatus = "UPDATE DoctorMaster SET Status = @p_Status , PGroup=@p_Group , @p_PDA wHERE (PLIC= @p_License);"
' ... Make a SQL call to update the database ...
'UpdatePhysician
Dim strConn As String
strConn = ConfigurationSettings.AppSettings("ConString")
If strConn = String.Empty Then
myConn = New SqlConnection()
Else
myConn = New SqlConnection(strConn)
End If
myConn.Open()
Dim daPhysician As New SqlDataAdapter()
Dim comUpdate As New SqlCommand()
comUpdate.Connection = myConn
daPhysician.UpdateCommand = comUpdate
comUpdate.CommandType = CommandType.Text
comUpdate.CommandText = strUpdateStatus
'Return the DataGrid to its pre-editing state
comUpdate.Parameters.Add(New System.Data.SqlClient.SqlParameter("@p_Status", System.Data.SqlDbType.Char, 3, "Status")).Value = strStatus
comUpdate.Parameters.Add(New System.Data.SqlClient.SqlParameter("@p_Group", System.Data.SqlDbType.NVarChar, 15, "PGroup")).Value = strGroup
comUpdate.Parameters.Add(New System.Data.SqlClient.SqlParameter("@p_License", System.Data.SqlDbType.NVarChar, 15, "PLIC")).Value = strLicense
 
comUpdate.Parameters.Add(New System.Data.SqlClient.SqlParameter("@p_PDA", System.Data.SqlDbType.Bit, "PDA")).Value = CType(e.Item.FindControl("ckPDA"), CheckBox).Checked.ToString

comUpdate.ExecuteNonQuery()

comUpdate.Dispose()
 
Thanks.
It kept givimg me data  format error.

View 1 Replies View Related

Insert Into Two Tables, Both With Auto Increment Fields

Jul 20, 2005

Just when I though I knew what I was doing. I ran into a roadblock.I have two tables, organizations & usersI am building a form online for orgs to input their own information.How do I insert into both tables when the org table needs to know what theuser_id is, but the user_id hasn't been created until the form is submitted?Any help or request for additional info would be more than great.Thanks!

View 1 Replies View Related

Insert NULL Values To Foreign Key Fields

Jan 15, 2008

Hi all,

I have a projects table with 2 foreign key fields that both link to the same employees table because a project has a Package Engineer (PkgEngineerID) and a Contract Administrator (PkgContrAdmin). When I try to insert a record with null values for either or both of these foreign keys I get an error:

The data in row xxx was not commited. The record can't be added or changed. Referential integrity rules require a related record in table 'tblEmployees'. The transaction ended in the trigger. The batch has been aborted.

An insert statement for the above would look something like the following:

INSERT INTO tblPackages (PkgNo, PkgName, PkgEngineerID, PkgContrAdmin, PkgRemark)VALUES (1234, 'My Package', NULL, NULL, 'My Package remark')

And the create table statements are:

USE [PASSQL]GO/****** Object: Table [dbo].[tblPackages] Script Date: 01/15/2008 23:25:26 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[tblPackages]( [ID] [int] IDENTITY(1,1) NOT NULL, [PkgNo] [nvarchar](20) NULL, [PkgName] [nvarchar](255) NULL, [PkgEngineerID] [int] NULL, [PkgContrAdmin] [int] NULL, [PkgRemark] [nvarchar](255) NULL, [upsize_ts] [timestamp] NULL, CONSTRAINT [aaaaatblPackages_PK] PRIMARY KEY NONCLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOALTER TABLE [dbo].[tblPackages] WITH NOCHECK ADD CONSTRAINT [FK_tblPackages_tblEmployees] FOREIGN KEY([PkgEngineerID])REFERENCES [dbo].[tblEmployees] ([ID])GOALTER TABLE [dbo].[tblPackages] CHECK CONSTRAINT [FK_tblPackages_tblEmployees]GOALTER TABLE [dbo].[tblPackages] WITH NOCHECK ADD CONSTRAINT [FK_tblPackages_tblEmployees1] FOREIGN KEY([PkgContrAdmin])REFERENCES [dbo].[tblEmployees] ([ID])GOALTER TABLE [dbo].[tblPackages] CHECK CONSTRAINT [FK_tblPackages_tblEmployees1]

And:

USE [PASSQL]GO/****** Object: Table [dbo].[tblEmployees] Script Date: 01/15/2008 23:28:01 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[tblEmployees]( [ID] [int] IDENTITY(1,1) NOT NULL, [EmpName] [nvarchar](255) NULL, [EmpShort] [nvarchar](255) NULL, [upsize_ts] [timestamp] NULL, CONSTRAINT [aaaaatblEmployees_PK] PRIMARY KEY NONCLUSTERED ( [ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
Any ideas on how to accomplish this would be great!
Thanks in advance!

View 4 Replies View Related

Refer To Webform Fields In Insert Statement

Aug 3, 2007

Can someone help with this? Let me know if what I'm trying to do is possible...

Here's code example:


@ClientID int,

@QuoteID int,

@Base real,

@One real,

@DwellingLimit real

AS

BEGIN

Insert Into tblOne(ClientID,QuoteID,GuideID,GuideRate,GuideMult,Premium)

Select @ClientID, @QuoteID, GuideID,GuideRate, @+"GuideMult"+,GuideRate*GuideMult

From tblTwo

Where Choose = 'True';

END


I need the value stored in tblTwo.GuideMult (ie. One, BaseRate) to be translated
into the numerical value shown on a webform (ie. @One, @BaseRate) and then
insert the numerical values into tblOne.GuideMult

Clear as mud? Does somebody have a better way to do this?

View 1 Replies View Related

Help-insert One Table To Another From Tow Date Fields- Single Row For Each Day

Apr 20, 2008

need help on update from one table to another like this
this is my first table

tb_all_holiday





id

fname

Start_Date

End_Date

val_holiday

111
aaaa

15/03/2008
21/03/2008

1

222
bbbb

02/05/2008
09/05/2008

3

333
cccc

03/04/2008
15/05/2008

4

333
cccc

29/04/2008
07/07/2008

1

444
dddd

01/05/2008
02/05/2008

1

444
dddd

09/05/2008
19/08/2008

1

555
EEE

09/07/2008
09/08/2008

4

666
fff
10/09/2008
12/09/2008

1
this is my second table to insert into !

i need to insert to another table like this
single row for each day from start_date TO END_DATE
check each employee add row for each day
insert all employee one after one


ID fname new_date val_holiday
----------------------------------------------------

111 aaaa 15/03/2008 1
111 aaaa 16/03/2008 1
111 aaaa 18/03/2008 1
111 aaaa 19/03/2008 1
111 aaaa 20/03/2008 1
111 aaaa 21/03/2008 1

222 bbb 02/05/2008 3
222 bbb 03/05/2008 3
222 bbb 04/05/2008 3
222 bbb 05/05/2008 3
222 bbb 06/05/2008 3
222 bbb 07/05/2008 3
222 bbb 08/05/2008 3
222 bbb 09/05/2008 3

333 ccc 03/04/2008 4
333 ccc 04/04/2008 4

......................................................add row for each day
...............................
333 ccc 15/05/2008 4


TNX for help

View 6 Replies View Related

Insert Diffrent Columns,Determine Non Unique Fields

Sep 19, 2006

andre writes "I have two questions:

1.)How do i determine if fields are not unique??
2) How to update one table with values from another table when the row names are diffrent??

Thank you!!"

View 1 Replies View Related

Row Number On Insert

Feb 27, 2008

Hello,

I am inserting a few records for test in a table:

insert into dbo.Articles(ArticleID, BlogID, AuthorID, Body)
select
newid(),
BlogID,
UserID,
'Body ' + cast(n as nvarchar)
from (select n, newid() as ArticleID, BlogID, UserID
from @Numbers
cross join dbo.Blogs
cross join dbo.Users) as DummyData
where n <= @articles

In my Body column I get Body 1, Body 2, Body 1, ...

What am I doing wrong?

What should I do to get Body 1, Body 2, Body 3, Body 4, ...

Thanks,
Miguel

View 3 Replies View Related

SQL 2012 :: Concatenate Fields And Insert Comma Between - How To Handle Nulls

Sep 5, 2014

I thought it's easy but somehow got lost, what is the good way to insert that Comma intelligently, depending if any of var value is NULL.

-- DECLARE @var1 varchar(10) = 'alpha1', @var2 varchar(10) = 'bravo2', @var3 varchar(10) = 'charlie3',@var4 varchar(10) = 'delta4'
DECLARE @var1 varchar(10) = 'alpha1', @var2 varchar(10) = NULL, @var3 varchar(10) = 'charlie3',@var4 varchar(10) = 'delta4'

SELECT ss= (CONCAT(@var1, + iif(COALESCE(@var1,@var2,@var3,@var4) IS NULL,'',', '),
@var2, + iif(COALESCE (@var2,@var3,@var4) IS NULL,'',', '),
@var3, + iif(COALESCE( @var3,@var4) IS NULL,'',', '),
@var4) )

View 3 Replies View Related







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