I have two tables. They both have an identity field to join them together. One of the tables has a column of data that I want to put in the other table. I need to make sure the data is brought over using the join so it updates that column for the right record.
I am struggling with this. Should I use a update or an insert? I'm leaning toward update but I can't figure out how with the join.
This is what I have tried so far:
Update grpcon.GroupID = groups.GroupID
from grpcon Inner Join groups
on grpcon.GroupNum=groups.GroupNum
Okay, after I got everything imported, I found that a few thousand columns had "Shifted" on me. So now I am trying to "Shift them over" to where they need to be.
I did this: INSERT INTO dbo.TABLENAME (COLUMN_NAME_TO_BE POPULATED) SELECT COLUM_NAME_OF_INFO_TO_BE_MOVED FROM dbo.TABLENAME WHERE MFG = 'MANUFACTURER_NAME' AND PN LIKE '8888888888' GO
I populated the PN column with 8888888888 to use as a reference point, and the MFG column already was populated with the correct name, so I was using those as my unique reference points.
Other columns that have the same MFG name are correct, so I have to use two unique identifiers to specify the actual data that needs to be moved.
It inserted 'NULL' in the whole table after I ran it in the Query Analyzer. It appeared to disregard the WHERE statement all together Any ideas on what I am doing wrong here?
Is there a way to move the data from one column to the next one over by specifying other WHERE criterias?
I am looking for a solution to move all Part Numbers for a specific manufacturer that is 9 digits long to a new column.
Let me explain............
I have a product table that has three columns of product codes associated with that product (Part Number as PN, Series as Series, and Industry Code as ICDE). I now want to create a fourth column (Manufacturer Code as MCDE) as my database has grown for another product specific numerical designator that is specific for one manufacturer.
Currently I have the specific 9 digit codes in the same column as the Part Numbers, though they all have their specific rows (Part Numbers & Manufacturer Codes are not in the same cell).
Now the Part Numbers have various numbers, letters, and special characters, but the specific 9 digit manufacturer codes are pure numbers.
So my question is............
How does one go about moving these specific 9 digit codes to their new column and out of the Part Number column?
They will all be exactly 9 digits, no special characters, no letters, no spaces.
Is there a way to tell MS SQL to just move anything for that specific manufacturer that has the 9 digit manufacturer numbers to the new column, bypassing anything with letters, special characters or any part number that is not a pure 9 digit number?
need some help converting a table which has one row for each year. Displaying the data so the each row will contain all of the information for the title and all of the years displayed in separate columns.
I have a SQL Querry which returns the data looking like this (the querry is grouping by Title and by year, then adding up the quantity of rows):
Basic Information needed for Life Insurance 25 2005 Basic Information needed for Life Insurance 45 2006 Ea Chairmans Conference 10 2005 EA Chairmans Conference Press Release 33 2005 EA Chairmans Conference Press Release 21 2006 EA Chairmans Inner Circle Press Release 16 2005 EA Chairmans Inner Circle Press Release 46 2006 EA Honor Ring Press Release 13 2005 EA Honor Ring Press Release 35 2006 EA National Conference Press Release 6 2005 EA National Conference Press Release 9 2006
I need this data displayed like this:
Title 2005 2006 Basic Information needed for Life Insurance 25 45 Ea Chairmans Conference 10 10 EA Chairmans Conference Press Release 33 21 EA Chairmans Inner Circle Press Release 16 46 EA Honor Ring Press Release 13 35 EA National Conference Press Release 6 9
What I want to do is to basically say:
If Row 1 Title = Row 2 Title and Row 1 Year = Row 2 (Year + 1)) Then
add to grid Row 1 Title, Row 1 Qty, Row 2 Qty
Skip Row 2 and go to Row 3 (repeat this step until end of data)
End
Is there any way in the SQL querry to retrieve this data in this format so that I can display it in a datagrid?
Is there any way to display the data in this pattern.
Below is the code I am using now, but since the moving of the data is done in code it is very slow. ****************** Global Variables
Dim dbName As String = "Region_Web_Page_Hits" Dim ColumnCount As Integer
Function ReturnColumnHeaderAndHitsDataSet() As System.Data.DataSet '******** This will bring back the column Headers and Gross Hits per Column Dim ColumnHeaderAndHitsQueryString As String = "SELECT DISTINCT TOP 100 PERCENT " & _ "YEAR(dat_Date) AS str_Year, COUNT(str_PageName) AS int_YearHits " & _ "FROM dbo.tbl_web_page_hits " & _ "WHERE (str_URL LIKE N'%press_Release%') " & _ "GROUP BY YEAR(dat_Date) " & _ "HAVING (Not (Year(dat_Date) Is NULL)) " & _ "ORDER BY YEAR(dat_Date)"
Dim ColumnHeaderAndHitsDataSet = LoadDataArray(ColumnHeaderAndHitsQueryString, dbName) Return ColumnHeaderAndHitsDataSet End Function
Function ReturnTableDataSet() As System.Data.DataSet 'This query string will return the data needed to display the report. Dim TableQueryString As String = "SELECT TOP 100 PERCENT " & _ "str_PageName, COUNT (str_PageName) AS int_Hits, YEAR(dat_Date) AS str_Year " & _ "FROM dbo.tbl_web_page_hits WHERE str_URL LIKE '%Press_Release%' " & _ "GROUP BY str_PageName, YEAR(dat_Date) ORDER BY str_PageName" Dim TableDataSet = LoadDataArray(TableQueryString, dbName) ColumnCount = TableDataSet.Tables(0).Columns.Count Return TableDataSet End Function
'******* Function to Load the Data Array Function LoadDataArray(ByVal queryString, ByVal dbName) As System.Data.DataSet Dim ConnectionString As String = ConnectionStr(dbName) Dim sqlConnection As SqlConnection = New SqlConnection(ConnectionString) Dim sqlCommand As SqlCommand = New SqlCommand(queryString, sqlConnection) Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand) Dim dataSet As DataSet = New DataSet dataAdapter.Fill(dataSet) sqlConnection.Close() Return dataSet End Function
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then Dim Sort_Field As String = "" dg_Data.DataSource = QueryMethod(Sort_Field) dg_Data.DataBind() End If End Sub
Currently I have a bunch of Classic ASP code which puts the data in to an array and then into a table with a series of if statments, but it is really slow.
I want to bind it to a data grid and if possible let the SQL statement format the data for me.
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
hi all, is there any query to move certain data from a sql data to access table through query. i am having a requirement where i have to fetch the records from a sql table that falls within a specified range to a ms access table. is this possible through a query.
We need to move duplicate data from this sheet to other table also having issue that sometime verifiedmemberID is null as well as verifiermember name is null and also having the values in BCP authorisationcode as well as FPoveridecode but transactionmode/bcpmode is 'n' and also having condition that transactionmode/bcpmode is 'y' but bcpauthorisationcode is blank.
I have a production application that I am building some upgrades usinga second (empty) copy the database. A few of the upgrades includedchanging the datatypes of a few fields from varchar to int(all thevalues in this column are already numbers)I am not trying to move the data from the production database into theblank database using DTS and the fields that had their datatypeschanged are getting dropped by dts.Is there anyway to move this data easily through dts or through anothermethod and not have the fields with the datatype changes get dropped?I have about 60 tables so it is not as simple as just copying andpasting the data..
I have two tables say A and Archive. After a certain period of time some records are to be sent to archive table.To copy records to archive table I am using SqlBulkCopy operations.Now I have to delete the records from A Table. I was thinking of sending a Comma seperated id's of rows that are to be deleted to a stored procedure.Are there any better techniques to move data to archive table and to remove data from main table.?Thanks.
Hey all, Another varbinary question. I am trying to move an image stored in a table varbinary(max) directly from one table to another programmatically. The rest of the data is just nvarchar(50) so I just use a T-SQL select statement in the code behind and feed all of the date into an SqlDataReader, I do this becuse there is some user interaction when the data is moved, so there may be some new values updated when transfering from one table to another, so once the old and possibly new data is stored in seperate variables then I use a T-SQL insert statement to move all of the data into the other table. Problem is I am not really sure how to handle the image data(varbinary(max)) to just do a straight up transfer from the one table to another. I get conversion errors when trying to handle the data as a string which makes sense. Not sure what to put for code examples since I really am stumped with this, but here is what is not working. Dim imageX As String SqlDataReader Code - imageX = reader("imageData") Insert code - myCommand.Parameters.AddWithValue("@imageData", imageX) Thanks in advance,
I have an application , user will read information in Excel file and insert that data into my application, I think it spend a lot of time. I want to make a tool which move data from Excel file to a table in My application (MS SQL) automaticly. How to do it, anybody has tool or know how to do, pls help me.thanks.
There is a table in which the data is coming in a massive rate, what are the ways to move those data from that table to another DB in another server (kind of archiving).
I would like to move the data / findings into a perm table?The reason for this is so clients can connect to the table using excel. I have another stored procedure which is setup in this process already and it works well. I basically have the stored procedure setup on a task to run early in the morning so when clients get up they connect and get their data.
USE [MMAUDIT] GO CREATE PROCEDURE [dbo].[MMA_AUDIT_QUESTIONS_SUMM_STG] AS BEGIN
first, i want filter data from table A if IC_NO and passport_Number no is null
then after get the result, i want move the result into table B. my table as below:Table A NUMBER IC_NO PASSPORT_Number ======= ====== =========== 1. 123 A123 2. 3. 456 A456
update a tables value(a single column), based on a query of another database, using a common column.
Here's what I've cooked up so far:
Declare @trackingNo nvarchar (50) Set @trackingNo = ( select tracking_no from P21_Shipping.dbo.shipping_data t1 inner join P21.dbo.oe_hdr t2 on t1.order_no = t2.order_no
[Code] ...
print @trackingNoThe error it's returning is:
Msg 512, Level 16, State 1, Line 3 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
So, I'm wanting to query Shipping_data for order_No that matches the same orderNo column value in P21 Database(oe_hdr table), then update P21 oe_hdr table with "trackingNo from Shipping_data
I'm creating a sql stored procedure inside this proc it returns some information about the user, i.e location, logged in, last logged in, etc I need to join this on to the photos table and return the photo which has been set as the profile picture, if it hasn't been set then return the first top 1 if that makes sense?
The user has the option to upload photos so there might be no photos for a particular user, which I believe I can fix by using a left join
My photos table is constructed as follows:
CREATE TABLE [User].[User_Photos]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [UserId] [bigint] NOT NULL, [PhotoId] [varchar](100) NOT NULL, [IsProfilePic] [bit] NULL,
[Code] ....
Currently as it stands the proc runs but it doesn't return a particular user because they have uploaded a photo so I need to some how tweak the above to return null if a photo isn't present which is where I'm stuck.
Not sure if this is ever going to be possible, but I'm trying to do a dynamic join on EXECUTE, but the execution string has to come from a table column.... i.e
select * from (select table1.theSql,table1.userid from table1 ) as a
Hi all,A (possibly dumb) question, but I've had no luck finding a definitiveanswer to it. Suppose I have two tables, Employees and Employers, whichboth have a column named "Id":Employees-Id-FirstName-LastName-SSNetc.Employers-Id-Name-Addressetc.and now I perform the following join:SELECT Employees.*, Employers.*FROM Employees LEFT JOIN Employers ON (Employees.Id=Employers.Id)The result-set will contain two "Id" columns, so SQL Server willdisambiguate them; one column will still be called "Id", while theother will be called "Id1." My question is, how are you supposed toknow which "Id" column belongs to which table? My intuition tells me,and limited testing seems to indicate, that it depends on the order inwhich the table names show up in the query, so that in the aboveexample, "Id" would refer to Employees.Id, while "Id1" would refer toEmployers.Id. Is this order guaranteed?Also, why does SQL Server use such a IMO brain-damaged technique tohandle column name conflicts? In MS Access, it's much morestraightforward; after executing the above query, you can use"Employees.Id" and "Employers.Id" (and more generally,"TableNameOrTableAlias.ColumnName") to refer to the specific "Id"column you want, instead of "Id" and "Id1" -- the"just-tack-on-a-number" strategy is slightly annoying when dealing withcomplex queries.--Mike S
I want to join the data to display a table that has the following information: Prod Idesc Prodchid Idesc Req Level T880A120 Assy-network 103P789 N.Resitor 1 4 T881A121 Assy-IC 275P246 IC 2 5
Is it possible to insert data into a table from a temporary table that is inner join? Can anyone share an example of a stored procedure that can do this? Thanks, xyz789
Hi all, I am not over familiar with SQL, I am a VB programmer, simply I need to achieve the following within Enterprise Manager.
I have 2 tables, different designs, different number of rows, I simply need to check whether the contents of a column in the first table is in a column in the second table, just simply a table/column to table/column data check for the same data content.
Easy Peasy for you guys, any help would be appreciated.
I have a datatable : Data_Table and a look up table: Lk_table. Myfield that I use in Inner Join is defined in both the data and look table.
So I build my query like this:
SELECT * FROM dbo. Data_Table INNER JOIN
dbo. Lk_table ON dbo.Data_Table.MyField = dbo.Lk_table.Myfield
The pb, sometimes I have myfield still with its default null value in the datatable: Data_Table. So, I end up getting 0 record when I execute the query shown above.
How do I turn that around so that even if myfield in Data_Table is Null, I still get the records from Data_Table. (I don t want a set of records including all possible values from the look up table: Lk_Table)
I have a XML data passed on to the stored proc in the following format, and within the stored proc I am accessing the data of xml using the nodes() method
Here is an example of what i am doing
DECLARE @Participants XML SET @Participants = '<ArrayOfEmployees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Employees EmpID="1" EmpName="abcd" /> <Employees EmpID="2" EmpName="efgh" /> </ArrayOfEmployees >'
SELECT Participants.Node.value('@EmpID', 'INT') AS EmployeeID, Participants.Node.value('@EmpName', 'VARCHAR(50)') AS EmployeeName FROM @Participants.nodes('/ArrayOfEmployees /Employees ') Participants (Node)
I have two table, tblCharge and tblSentence, for each charge, there are one or more sentences, if I join the two tables together using ChargeID such as: select * from tblCharge c join tblSentence s on c.ChargeID=s.ChargeID , all the sentences for each charge are returned. There is a field called DateCreated in tblSentence, I only want the latest sentence for each charge returned, how can I do this? I tried to create a function to get the latest sentence for a chargeID like the following: select * from tblCharge c join tblSentence s on s.SentenceID=LatestSentenceID(c.ChargeID) but it runs very slow, any idea to improve it? thanks,
I built a query that brings in 'Discounts' (bolded) to the Order detail by using the bolded syntax below. I started off by running the query without the bolded lines and got exactly what I was looking for but without the ‘Discount’ column. When I tried to add the ‘Discount’ into the query, it duplicated several order lines. Although total ‘Discount’ column ties out to the total amount expected in that column, ‘Total Charges’ are now several times higher than before.
For example, I get 75 records when I run without the bolded syntax and I get several hundred results back when adding back in the bolded syntax when i should still be getting 75 records, just with an additional column ‘PTL Discount’ subtotaled.My question is, how to I introduce a new select or join from another table without duplicating the original data?
If on the source I have a new column, the script generated by SqlPackage.exe recreates the table on the background with moving the data into a temp storage. If the table is big, such approach can cause issues.
Example of the script is below: in the source project I added columns [MyColumn_LINE_1] and [MyColumn_LINE_5].
Is there any way I can make it generating an alter statement instead?
BEGIN TRANSACTION; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; SET XACT_ABORT ON; CREATE TABLE [dbo].[tmp_ms_xx_MyTable] ( [MyColumn_TYPE_CODE] CHAR (3) NOT NULL,
[Code] ....
The same script is generated regardless the table having data or not, having a clustered or nonclustered PK.
I have a requirement of table partitioning. we have 10 years of data on a table which is 30 billion up rows on 2005 server we are upgrading it to 2014. we have to keep 7 years of data. there is no keys on table or date column. since its a huge amount of data and many users its slow down the process speed. we are thinking to do partition on 7 years for Quarterly based. but as i said there is no date column on table we have to use reference table to get date. is there a way i can do the partitioning with out adding date column on table? also does partition will make query faster?
I have think three ways to do it. 1. leave as it is. 2. 7 years partition on one server 3. 3 years partition on server1 and 4 years partition on server2 (for 4 years is snapshot better?)