Transact SQL :: XML Data Column - Insert Into Another Table

May 29, 2015

I have table with about 10000 rows,  there is a column named  Raw_XMLData is defined as varchar but data is xml format.  

I try to insert into another table, if Raw_XMLData column has is valid xml data?

Is it possible to do in T sql?

View 2 Replies


ADVERTISEMENT

Transact SQL :: Populate Column On Insert Based On Value From Another Table

Jul 26, 2015

I have the following 2 tables:

Table: classes  Columns: classID, hp
Table: char_active  Columns: name, classID, hp

The classes table is already populated.

What I want to do is insert a new row into char_active using the name and classID column, and have the HP column auto populate based on the corresponding value in the classes table. This is the trigger I wrote but I'm getting the error

Incorrect syntax near 'inserted'.

I'm new to sql, this is actually the first trigger I've tried writing. 

create trigger new_hp on curr_chars.char_active
instead of insert
as
declare @hp tinyint
select @hp=lists.classes.hp from lists.classes where lists.classes.classID=inserted.classID
insert into curr_chars.char_active (name, classID, hp) inserted.name, inserted.classID, @hp
go

View 4 Replies View Related

Transact SQL :: How To Insert Dynamic Column Values Of A Table To Variables

Jul 18, 2015

I am trying to insert different number of columns into variables.  This is what it does If I use a static columns.

declare @AccountType nvarchar(10)
declare @Total numerical(15,2)
declare @1 numerical (15,2)
declare @2 numerical (15,2)
declare @3 numerical (15,2)

#MonthtoDate  temp table is created using a dynamic pivot query. 

Data looks like this :

Account Type  1 2
3 Total
Type 1 3
0 4 7
Type 2 5
7 1 13

Select @AccountType = AcctType , @Total = MonthToDate, @1 = [1], @2 = [2], @3 = [3]  from #MonthtoDate 

However the issue is with [1],[2],[3] columns. Those are the number of days of the month. If today is the 3rd day of the month, we only need to show 3 days. So the final table has column [1],[2],[3] and @AccountType and @Total .

We want to run this query everyday to get the moth to date values.If we run this tomorrow, it will have 4 date columns [1], [2],[3],[4] and @AccountType and @Total .

View 6 Replies View Related

Transact SQL :: Insert Data From Temp Table To Other Table

Oct 5, 2015

I want to insert the data from temp table to other table. Only condition is, it needs to sorted based on tool number and tool date. For example if we have ten records for tool number 1000, it should be order by tool number and then based on tool_dt. Both tables doesn't have any primary keys. Please find below my code. I removed all the unnecessary columns for simple understanding. INSERT INTO tool_summary  (tool_nbr, tool_dt) select tool_nbr, tool_dt from #tool order by tool_nbr, tool_dt...But this query is not working as expected. Data is getting shuffled.

Actual Data
Expected Result

1000
1-Aug
1000
1-Feb
1000
1-Jul
1000

[code]....

View 3 Replies View Related

Transact SQL :: INSERT Specific Data To Other Table

Aug 10, 2015

I am still learning T-SQL .Lets consider the table below, ID 1-3 shows our purchase transactions from various Vendors and ID 4-6 shows our payments to them

Table 1 - VendorTransactions

ID     PARTY    AMOUNT   VOUCHER
---------------------------------------
1       A               5000              Purchase
2       B               3000              Purchase
3       C               2000              Purchase

4       A               3000              Payment
5       B               1000              Payment
6       C               2000              Payment
7       A               1000              Payment


Now we have a blank table Table 2 - Liabilities

ID     PARTY    AMOUNT 

I want that SQL should look for each individual party from Table 1 and Calculate TOTAL PURCHASE and TOTAL PAYMENTS and then deduct TOTAL PAYMENTS from TOTAL PURCHASE so we get the remaining balance due for each party and then add the DIFFERENCE AMOUNT alongwith PARTY to the TABLE 2 so I can get the desired result like below

ID     PARTY    AMOUNT
-------------------------
1       A               1000              
2       B               2000              
3       C               0       

View 3 Replies View Related

Transact SQL :: Insert Duplicate Data From One Table To Another

May 14, 2015

i am having three tables

test
testId  testName  totalQuestion

Questions

QuestionId  fktestId  QuestionName

Now i am trying to insert a duplicate copy test by passing testId..Here is my sp

if not EXISTS(SELECT testName from tblTest WHERE UPPER(@testName) = UPPER(@testName))
BEGIN
INSERT INTO tblTest SELECT @userId, testName,duration,totalQuestion,termsCondition,0,GETUTCDATE(),GETUTCDATE() from tblTest WHERE id=@testId
SET @insertedTestId=@@identity
INSERT INTO tblTestQuestion SELECT @insertedTestId,question,0,GETUTCDATE(),GETUTCDATE() from tblTestQuestion WHERE testId=@testId
END

how to insert in answer table as one question can be multiple answers.

View 4 Replies View Related

Transact SQL :: Key And Indexes On Two Column Data Table Or Parsed View (Large String Of Data And Filename)

Oct 4, 2015

I am studying indexes and keys. I have a table that has a fixed width of data to be loaded in the first column which is parsed in a view based on data types within the fixed width specifications.

Example column A:
(name phone house cost of house,zipcodecountystatecountry)
-a view will later split this large varchar string based 
column b: is the source filename of the data load (varchar 256)
....

a. would there be a benefit of adding a clustered or nonclustered index (if so which/point in direction on why)

b. is there benefit of making one of these two columns a primary key (millions of records) or for adding a 3rd new column as a pk?

c. view: this parses the data in column a so it ends up looking more like "name phone house cost of house zipcode county state country" each having their own column.

-any pros/cons of adding indexes (if so which) to the view instead of the tables or both for once the data is parsed?

View 4 Replies View Related

Transact SQL :: Insert Data To Different Table From Other Table

Aug 22, 2015

we have a table below

TABLE1
ID         Roll        Name         Amount     . . . . . . so on
---------------------------------------
1            2           Alex            500
2            5           Jones          600
3            2           Ales            400

and we have TABLE 2

ID         Roll        Name         Amount   . . . . . . . so on

In both the Tables ID Field is Identity Field and rest all the columns are identical in both the tables.I want to perform a query in such a way that SQL Should,

1) Remove all data from TABLE2 First
2) Select those records from TABLE1 where Roll = 2
3) Then, Insert the results to TABLE 2

So we should get the result similar to below:

ID         Roll        Name         Amount   . . . . . . . so on
---------------------------------------
1            2           Alex            500
3            2           Ales            400

how can I do this in a same sql statement.

View 3 Replies View Related

Transact SQL :: Method To Generate Insert Statements For Data In A Table

May 30, 2013

I have a database which will be generated via script. However there are some tables with default data that need to exist on the database.I was wondering if there could be a program that could generate inserts statments for the data in a table.I know about the import / export program that comes with SQL but it doesnt have an interface that lets you copy the insert script and values into an SQL file (or does it?)

View 7 Replies View Related

Transact SQL :: Table Row Data Show In Column Data

Oct 22, 2015

I have a simple table data i want want to show row data in to column data.
      
SELECT clblcode,mlblmsg
FROM warninglabels

My expected result will be 

0001                 0002  0003                      0004
-------                ------- --------                    --------
May Cause....       Important.....  Take madi...........         Do Not Take.......

View 16 Replies View Related

Transact SQL :: Display Different Table Having Same Column With Different Data

Sep 25, 2015

I am having two table i.e( tbl_oldEmployee , tbl_NewEmployee ),which is having Column name Employee Name and City same in both table but inside column data is different in different table.but i want to view the Employee name and City from tbl_NewEmployee to tbl_oldEmployee which is having EmployeeId common with tbl_oldEmployee extra record also required (i.e  tbl_NewEmployee having 6 record  and tbl_oldEmployee having 10 record,so i need to display data from  tbl_oldEmployee but first 6 record which id match with tbl_NewEmployee id should be replaced and extra data from tbl_oldEmployee also display).

View 3 Replies View Related

Transact SQL :: Find Table And Column Names From String Data

May 29, 2015

I have a SQL text column from SP_who2 in table #SqlStatement:

like 1row shown  below :

 "update Panel  set PanelValue=7286 where PanelFirmwareID=4 and PanelSettingID=9004000"

I want to find what table and column  names are in the text ..

I tried like below ..  

Select B.Statement from #sp_who2 A  
LEFT JOIN #SqlStatement B ON A.spid = B.spid 
 where B.Statement IN (
SELECT T.name, C.name FROM sys.tables T
JOIN sys.columns C 
ON T.object_id=C.object_id
WHERE T.type='U'


Something like this : find the column names and tables name

View 18 Replies View Related

Insert Data TimeStamp Column In A Table

Jan 10, 2008

I have been provided with a table where one of the columns is of TimeStamp data type. My question is how to insert and update data in this column through my SQL Statement? When I run my SQL statement, it gives me an error with this column name in the error.

View 3 Replies View Related

Insert Data Into A Table Without Identity Column

Feb 6, 2008



Hi,
I need to insert data into a table using data flow task. Unfortunately this table's priamry key column (integer column) is not identity column. I am looking a way to get the primary key value for the new records. Please advice. Thanks

View 5 Replies View Related

Insert Statement That Pulls Column Data From Another Table?

Nov 3, 2006

hi.

i cant get this quite right.

i have a table and i need to insert one column with data from another table. it goes something like this (although i know this is wrong, just here for a visual explaination) :


Code:


INSERT INTO List
(list_date, email_address, list_status, list_email)
values
(
GetDate()
, 'name@rice.edu'
, 0
, SELECT emailAddress FROM Users WHERE id = '72'
)



so, list_email needs the email address from the Users
table. i tried messing around with inner joins but, well,
here i am...

thanks in advace.

View 5 Replies View Related

Problem In Using Sqlbulkcopy To Insert Data From Datatable(no Identity Column) Into Sql Server Table Having Identity Column

Jun 19, 2008

Hi,
I am having problem in bulk update of a sql server table haning identity column from a datatable( has no identity column) using sqlbulkcopy. I tried several approaches, but it does not show any error nor is the table getting updated. But the identity value seems to getting increased every time.
thanks.
varun

View 6 Replies View Related

Reading Values From Data-description Column And Insert Into One Table?

Jul 17, 2013

I have a subselect that should be working but doesn't. Been at it too long today.

DECLARE @Calendar1 AS DateTime
SET @Calendar1 = '{{{ Please choose a start date. }}}'
SELECT
('0' + CONVERT (varchar (10), W.WorkerID)) AS VendorID,
(W.FirstName + ' ' + W.LastName) AS VendorName,
(W.FirstName + ' ' + W.LastName) AS Contact,

[code].....

Where did I go wrong?

View 3 Replies View Related

Transact SQL :: How To INSERT Column Into MyTable

Jun 8, 2015

How to INSERT new column(Field) into MyTable

1. FirstName nvarchar(50)
2. LastName nvarchar(100)
3. Student bit Checked
4. CreateDate datetime
5. HwoOld float Checked

View 6 Replies View Related

Transact SQL :: Additional Column With Bulk Insert?

Aug 11, 2015

Need to know a mode whereby somehow I can every time insert an additional column in a table while bulk inserting data to an existing table from a new flat file thus identifying the file from which, or the time when, the data was inserted in an existing table.

View 2 Replies View Related

Transact SQL :: Key Increment Even On Failed Insert Into On One Column

May 28, 2015

The reason why cust_id started at #4 and not #1 is because I failed to insert property three times in a row for having "Tatoine" instead of "WI" or a state less than 5chars nchar(5) correct? Then when I did a valid statement, the row was created at the starting number of four. I imagine this prevents users from having duplicate cust_ids. This however is also where rollback and similar commands could be handy correct or is there something more obvious I'm missing on a failed "insert into" to not increment the cust_id. The three rows 1,2 and 3 do not exist I believe and are not null.  Having null values would of contradicted the table where two columns "not null" are a requirement.

CREATE TABLE customersnew
(
cust_idINTNOT NULL IDENTITY(1,1),
cust_nameNCHAR(50)NOT NULL,
cust_addressNCHAR(50)NULL ,
cust_cityNCHAR(50)NULL ,
cust_stateNCHAR(5)NULL ,

[code]...

View 2 Replies View Related

Transact SQL :: SUM Of Two Table Column Base On Another Column Value And SUBTRACT And Join Tables

Oct 14, 2015

I have the following table

Table Name EmployeeInformation
EmployeeID EmployeeFirstName EmployeeLastName
    1             |John                       |Baker
    2             |Carl                        |Lennon
    3             |Marion                    |Herbert

Table Name PeriodInformation
PeriodID PeriodStart PeriodEnd
    1        |1/1/14      |12/30/14
    2        |1/1/15      |12/30/15

[code]...

I want a query to join all this tables based on EmployeeID, PeriodID and LeaveTypeID sum of LeaveEntitlement.LeaveEntitlementDaysNumber based on LeaveTypeID AS EntitleAnnaul and AS EntitleSick and sum AssignedLeave.AssignedLeaveDaysNumber based on LeaveTypeID  AS AssignedAnnaul and AS AssignedSick and subtract EntitleAnnaul from AssignedAnnual based on LeaveTypeID  AS AnnualBalance and subtract EntitleSick from AssignedSick based on LeaveTypeID  AS SickBalance

and the table should be shown as below after executing the query

EmployeeID, EmployeeFirstName, EmployeeLastName, PeriodID, PeriodStart, PeriodEnd, EntitleAnnual, AssignedAnnual, AnnualBalance, EntitleSick, AssignedSick, SickBalance

View 4 Replies View Related

Transact SQL :: Instead Of Insert / Verify Not Inserting Into Identity Column

Apr 24, 2015

I am writing an Instead of Insert trigger. I would like to fire an error when inserting into an 'Identity' column. Since UPDATE([ColumnName]) always returns TRUE for insert statements, is there an easy/fast way around this? I don't want to use: 

IF(EXISTS(SELECT [i].[AS_ID] FROM [inserted] [i] WHERE [i].[AS_ID] IS NULL))
here is my pseudo-code...
CREATE VIEW [org].[Assets]
WITH SCHEMABINDING

[Code] .....

-- How does this statement need to be written to throw the error?
--UPDATE([AS_ID]) always returns TRUE

IF(UPDATE([AS_ID]))
RAISERROR('INSERT into the anchor identity column ''AS_ID'' is not allowed.', 16, 1) WITH NOWAIT;

-- Is there a faster/better method than this?
IF(EXISTS(SELECT [i].[AS_ID] FROM [inserted] [i] WHERE [i].[AS_ID] IS NOT NULL))
RAISERROR('INSERT into the anchor identity column ''AS_ID'' is not allowed.', 16, 1) WITH NOWAIT;

-- Do Stuff
END;

-- Should error for inserting into [AS_ID] field (which is an identity field)
INSERT INTO [org].[Assets]([AS_ID], [Tag], [Name])
VALUES(1, 'f451', 'Paper burns'),
(2, 'k505.928', 'Paper burns in Chemistry');

-- No error should occur
INSERT INTO [org].[Assets]([Tag], [Name])
VALUES('f451', 'Paper burns'),
('k505.928', 'Paper burns in Chemistry');

View 7 Replies View Related

Transact SQL :: Get Table And Column Name In Separate Column Using PIVOT

Jul 16, 2015

Is there a way we can get Table and Column name in separate column using PIVOT or something?Right now what i have is:

Text                                                     QueryPlan             Plan_handle  
         Name         Value

select id,name,Address from person     <showPlznXML...   010101                 Table            Person
select id,name,Address from person     <showPlznXML...   010101                 column         id
select id,name,Address from person     <showPlznXML...   010101                 Table            Person

[code]....

View 26 Replies View Related

Transact SQL :: Insert A Record Into Second table Where There Is Not A Match In First Table

Jun 25, 2015

I have a table in different databases with the same name.  My goal is to compare the two tables, and insert a record into the second table where there is not a match in the first table.  So far, my query looks like the following:

SELECT [metal] FROM [ProductionDatabase].[dbo].[Metalurgy]
EXCEPT
SELECT [metal] FROM [TestDatabase].[dbo].[Metalurgy]

This gives me a list of records from [Production].[dbo].[Metalurgy] which do not reside in [TestDatabase].[dbo].[Metalurgy].  Now, I need to use that list to insert missing records into [TestDatabase].[dbo].[Metalurgy].  How can I modify the above code to INSERT the missing records?

View 4 Replies View Related

SQL Server 2008 :: Insert Data Into Table Variable But Need To Insert 1 Or 2 Rows Depending On Data

Feb 26, 2015

I am writing a query to return some production data. Basically i need to insert either 1 or 2 rows into a Table variable based on a decision as to does the production part make 1 or 2 items ( The Raw data does not allow for this it comes from a look up in my database)

I can retrieve all the source data i need easily but when i come to insert it into the table variable i need to insert 1 record if its a single part or 2 records if its a twin part. I know could use a cursor but im sure there has to be an easier way !

Below is the code i have at the moment

declare @startdate as datetime
declare @enddate as datetime
declare @Line as Integer
DECLARE @count INT

set @startdate = '2015-01-01'
set @enddate = '2015-01-31'

[Code] .....

View 1 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

Transact SQL :: Generate Insert With Column List And Select With Columnlist Statements

Oct 22, 2015

I had to enable identity_insert on a bunch of tables and I have already done that. Now I need to modify my insert into select * from statements to include column list names along with identity columns for select as well as insert statements. The DDL is same but they are both different databases.There are almost 100 tables that it needs to be modified. Is there a way we can generate scripts for insert and select for each individual table along with their column lists including the identity column?

View 7 Replies View Related

Transact SQL :: If Not Exists Some ID In One Table Then Insert ID And Description In Another Table

Jul 14, 2015

I need to find out if a Transaction ID exists in Table A that does not exist in Table B.  If that is the case, then I need to insert into Table B all of the Transaction IDs and Descriptions that are not already in. Seems to me this would involve If Not Exists and then an insert into Table B.  This would work easily if there were only one row.  What is the best way to handle it if there are a bunch of rows?  Should there be some type of looping?

View 12 Replies View Related

Transact SQL :: Using Bulk Insert - Invalid Column Number In Format File Error

Jun 5, 2015

I try to import data with bulk insert. Here is my table:

CREATE TABLE [data].[example](
 col1 [varchar](10) NOT NULL,
 col2 [datetime] NOT NULL,
 col3 [date] NOT NULL,
 col4 [varchar](6) NOT NULL,
 col5 [varchar](3) NOT NULL,

[Code] ....

My format file:

10.0
7
1  SQLCHAR 0  10 "@|@" 2 Col2 ""
1  SQLCHAR 0  10 "@|@" 3 Col3 ""
2  SQLCHAR 0  6 "@|@" 4 Col4 Latin1_General_CI_AS

[Code] .....

The first column should store double (in col2 and col3) in my table

My file:
Col1,Col2,Col3,Col4,Col5,Col6,Col7
2015-04-30@|@MDDS@|@ADP@|@EUR@|@185.630624@|@2015-04-30@|@MDDS
2015-04-30@|@MDDS@|@AED@|@EUR@|@4.107276@|@2015-04-30@|@MDDS

My command:
bulk insert data.example
from 'R:epoolexample.csv'
WITH(FORMATFILE = 'R:cfgexample.fmt' , FIRSTROW = 2)

Get error:
Msg 4823, Level 16, State 1, Line 2
Cannot bulk load. Invalid column number in the format file "R:cfgexample.fmt".

I changed some things as:
used ";" and "," as column delimiter
changed file type from UNIX to DOS and adjusted the format file with "
" for row delimiter

Removed this line from format file
1  SQLCHAR 0  10 "@|@" 2 Col2 ""
Nothing works ....

View 7 Replies View Related

Transact SQL :: How To Alter Existing Table Column As Identity Without Dropping Table

Nov 20, 2013

I have created a table as below mentioned. Then I want to alter the ID column as identity(1,1) without dropping the table as well as losing the data.

create table dbo.IdentityTest
(
id int not null,
descript varchar(255) null,
T_date datetime not null
)

View 7 Replies View Related

Transact SQL :: XML Column Data Into Separate Column

Nov 18, 2015

I have a column with the data as below :-

<Items>
  <Item Value="Value1" />
  <Item Value="Value2" />
<Items>

How to get this data into seperate columns as 

Items
value1
value2

View 2 Replies View Related

Cannot Insert The Value NULL Into Column SnapshotDataID, Table ReportServerTempDB.dbo.SessionData; Column Does Not Allow Nul

May 3, 2007

I receive this message when I try to run any report. The reportserver and reportservertempdb databases were upgraded using backup/restore from SQL2000 to SQL2005 on a separate server which is running RS2005 . Please help. Thanks

View 1 Replies View Related

Transact SQL :: Delete Records From Table (Table1) Which Has A Foreign Key Column In Related Table (Table2)?

Jun 29, 2015

I need to delete records from a table (Table1) which has a foreign key column in a related table (Table2).

Table1 columns are: table1Id; Name.  Table2 columns include Table2.table1Id which is the foreign key to Table1.

What is the syntax to delete records from Table1 using Table1.Name='some name' and remove any records in Table2 that have Table2.table1Id equal to Table1.table1Id?

View 11 Replies View Related







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