Transact SQL :: Clone Some Rows On Selection

Apr 20, 2015

I have a table in which I have defined 2 columns. First column is called 'name' and second is called 'number'.It looks like sample bellow:

Name        |    Number        |
---------------------------------
John          |    2                  |
Jessica       |    3                  |
Jack           |    2                  |
etc...

I need to make a query that will have the following results:

Name   |
----------
John     |
John     |
Jessica  |
Jessica  |
Jessica  |
Jack     |
Jack     |

John for 2 rows, Jessica for three rows and Jack for two rows. Is it possible only with loops or is there in SQL a duplicate/clone function...?

View 3 Replies


ADVERTISEMENT

Transact SQL :: Selection Criteria In DB1 - Need Fields In DB2

Sep 24, 2015

I need to query a table in Database 1 then, using a primary key, pull the columns from a table in Database 2.

The query I'm using in db_1 works:

SELECT * FROM db_1.table_1 WHERE  (hcpcs_cd = '20552' AND srvc_units_num>'1 ' AND claim_dos_yr >'2012') 

But what I really need are the columns associated with these records in db_2.table_1.  There is a primary key in both tables.

Ultimately what I need is all of the columns in db_2.table_1 and the hcpcs_cd, srvc_untis_num, and claim_dos_yr from db_1.table1

View 11 Replies View Related

Transact SQL :: First Values In Multiple Columns Selection

May 19, 2015

I'm trying to run something like this:

Select ID, FIRST(forename), FIRST(surname) from table1
GROUP BY ID;

I know First doesn't work in TSQL, I used to use it in Access and now need to run something like that in TSQL. Simply getting unique ID with first forename and surname, cause there are some dupes in a table.

There are records like:

ID      forename     surname
--------------------------------
1    John    Kormack
1   James  Dope
2   Erin    Dupes
3   Will  Hugh
3    Walter Heisenberg

So I want to pull out:

1 John Kormack
2 Erin Dupes
3 Will Hugh

How can I run it in TSQL?

View 6 Replies View Related

Transact SQL :: Table Trigger To Delete All Rows Before Inserting Rows

Jul 24, 2015

I have a SQL script to insert data into a table as below:

INSERT into [SRV1INS2].BB.dbo.Agents2
select * from [SRV2INS14].DD.dbo.Agents

I just want to set a Trigger on Agents2 Table, which could delete all rows in the table , before carry out any Insert operation using above statement.I had below Table Trigger on [SRV1INS2].BB.dbo.Agents2 Table as below: But it did not perform what I intend to do.

USE [BB]
GO
/****** Object:  Trigger    Script Date: 24/07/2015 3:41:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[code]....

View 3 Replies View Related

DB Clone

Sep 24, 2006

hellooI'm building an intranet accounting system, at the begining of each year the administrator must be able to create a new year DBfrom the applicationIs this possible knowing that im using SQL Server 2000, .net framework 1.1 Thank you in advanced

View 3 Replies View Related

Clone DB

Sep 25, 2006

Helloo

Can I backup DB programatically, and then restore it with different name also programatically??

meaning:
I have db2006, can I backup this db then restore it as db2007 programatically???using a stored procedure for example????

So by doing this the user will be using db2007 @ the begininng of the year and so on each year


I'm using sql2000

Please I need your help
Thank you

View 4 Replies View Related

How To Programmatically Clone A Database?

Jan 21, 2005

Howdy,

Is the any easy way to clone a database programatically?
I've searched the web but did not come up with anything.

At the moment I create a new blank database (based on the model database)
and create tables, indexes, etc. via asp. (The databases are always exactly
the same)

It seems to me that it would be a better option to
create one database with tables, indexes, etc and copy
it to a new database (on the same server).

One of the options I'm considering would be to create a database,
fill it with tables and indexes, etc. and then detach it.
Whenever I need a new database all I would have to do is use the
file system object to copy and rename the mdf file and then reattach the
new mdf file.

I realise that I could also make the changes to the model
database so that all new databases have the same structure
but that would be my last resort.

Is there any easier way to do this? A stored procedure perhaps?

You're opinions and advice would be welcomed.

View 5 Replies View Related

Clone New Database From Existing

Jan 19, 2007

How do I go about creating a cloned copy of an existing database on the same server? I basically want to set up a test copy of a production database, but let it reside on the same server with a slightly different name, prefixed with 'Testing_".

I typically just use Studio Express Manager and not scripts to do admin tasks. Here's what I tried that didn't work so well:

* Had full backups of production db
* Detached production database I wanted to clone
* From within Win Explorer, copy the .mdf and .ldf files within same data folder and gave them a new name, prefixing with "Testing_"
* Re-attached prodution db
* Attached "Testing_..." database

Sql Express seems confused at this point with new database I attached. It references the full path of the database I copied from (c:program filesmicrosoft sql servermssql.1data...". I rename the datbase, removing full path and prefixing with "Testing_".

* Using Sql authentication, changed the default database for the Login account to the new cloned copy of database.
* Did some query level data sanitizing to the cloned copy of the db. I am positive I performed this on the correct db.
* Was able to connect/authenticate to the cloned copy through a custom VB app on my dev machine, and all looked well.
* Tried to connect to the cloned db from another machine and couldn't. Went back to my dev machine and noticed the original production db looked hosed -- there were no tree nodes available to it! Was still able to connect to the cloned "Testing_" db copy, but not able to connect/authenticate anymore to the production copy.
* Detached cloned copy of "Testing_" db and moved it out of the data folder.
* Detached production db. Got an error msg indicating operation failure of some kind, but the database was gone from the tree.
* Reattached the production db but couldn't hit it from my custom vb app. Re-did the login and user accounts used by the app and was able to hit it. However, the data sanitizing I had done earlier in the cloned copy clearly was visibile in the production db!
* Had to restore production db from backup. Had problems authenticating from app, and recreated User account before the app was to connect.

Q1: What I am doing wrong? Sql Express was obviously as confused as me somewhere along the line.

Q2: Is specifying a default database used by a Login account necessary for a VB app like mine. I think it was something I discovered in the past, however, this would seemingly present a problem whenever I want my app to hit a different database, established through a connection string.

TIA...

Rick

View 10 Replies View Related

I Want To Clone An Instance Of SqlDataReader Type

May 2, 2008

hai
I need to copy an instance of SqlDataReader type. I perform a query and stores its details to an instance of SqlDataReader type. Now before i read it, i want to make a clone as i got to use it again just after sometime. I found something like ICloneable.Clone. But i couldnot find much on the internet as to how to use it. Can anybody give me a sample as to how to go about this

View 1 Replies View Related

SQL Server - 'cold' Database Clone, Was This Ok?

Jul 23, 2005

HiI was in the situation of cloning a SQL server database last night.Today, a dependent application was behaving a little erratically thoughmost things were fine after sorting out some ntfs permissions. I'verecovered this database from backup exec before from a hot-backup, thisis the first time I've attempted this procedure though.Could I check with the experts here as to whether what I did was OK?Been googling to see if it is really the right thing to do, haven'tcome up with anything definitive...Assume server SOURCE and DEST:install DEST to same specification, OS, SQL patch level as SOURCE. Samepaths where applicable.shut down SQL server on bothCopy all datafile folder (d:sqldata) which is the full databaseincluding MASTER etc all over to DEST.Shut SOURCE down.Rename DEST to SOURCE, disable SQL server starting, set networksettings to those of SOURCE and reboot.Wait for things to settle after reboot and name change, bring SQLdatabase up.Client application now connects, I can't see any problems, but therehave been some strange anomalies in satellite applications today. Allhave been bounced to see if it's just a change they needed to notice,to no avail.Was that an OK operation to have done, or is there something just aboutto bite me when I'm not looking?Be grateful for any advice, I spent today pulling a lot of hair out.Thanks in advance :)AW

View 3 Replies View Related

Sql Server Hot Backups (Clone/Fracture)

Aug 6, 2006

Not sure if there is anyway to do hots on sql server .From all I haveheard an EMC can do clones and fractures in order to implement a hotbackup or some kind of it in sql server.Seemingly the DBA has to do something toenable the fracture of the clone . Is anyone familiar with this ?Your input is highly appreciatedMB

View 1 Replies View Related

SQL Server 2008 :: Clone Hierarchy To Another Table

Apr 4, 2015

I have a table "t_prod_cat" which contains hierarchical data which is used in production to present data.

CREATE TABLE [dbo].[t_prod_cat](
[cat_node_id] [bigint] IDENTITY(1,1) NOT NULL,
[advertiser_id] [bigint] NOT NULL,
[cat_hid] [hierarchyid] NULL,
[level] AS ([cat_hid].[GetLevel]()) PERSISTED,
CONSTRAINT [PK_t_prod_cat] PRIMARY KEY CLUSTERED
(
[cat_node_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]

In order not to impact the production website during the time an advertiser is editing (the editing might take much time and also mainly because at any time during the editing, the advertiser could cancel all the changes he did), I was thinking of transferring all the data linked to that advertiser to another table and let the advertiser apply any modifications up to the moment he will commit the changes.

Therefore, I would like to "CLONE" the hierarchy related to a certain advertiser_id to another table "t_prod_cat_work"

CREATE TABLE [dbo].[t_prod_cat_work](
[temp_cat_node_id] [bigint] NOT NULL,
[temp_cat_hid] [hierarchyid] NOT NULL,
[advertiser_id] [bigint] NOT NULL
) ON [PRIMARY]

What can be the easiest way to clone all the hierarchical data (multi-levels) from 't_prod_cat' to 't_prod_cat_work' for a certain advertiser_id ?

View 2 Replies View Related

SQL Server 2008 :: Clone Stored Procedures From Database A To B

Apr 24, 2015

I have this requirement where some store procedures from a "seed" database need to be replicated to another database (on demand, so replication is not suppose to be use in this scenario).

I know it can be achieved by exporting the store procedures and then execute that at the B database but I want something a bit more automatic since it can be a large number of sprocs. I am trying something like this (still in dev):

SET NOCOUNT ON;
--
SELECT ROW_NUMBER() OVER(ORDER BY definition) seq, definition base
into #sprocs
FROM databaseA.[sys].[procedures] p
INNER JOIN databaseA.sys.sql_modules m ON p.object_id = m.object_id

[Code] ....

But I am sure there are way better ways to accomplish that...

View 4 Replies View Related

SQL Server 2012 :: Insert Clone Copy Of Records

May 24, 2015

I am having three table tblTest,tblTestQuestion,tblAnswers

Each test can have multiple question and each Question can have multiple answers.

Now I am already having records in database. I wants to create clone copy of existing test except testdetails in tblTest because the test will be unique, and then insert questions and answers into their respective tables.

I was trying to create SP but stuck.

Please find below tables structure

[code="
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblAnswer](

[Code].....

View 5 Replies View Related

SQL Server Admin 2014 :: Clone SSRS VM For Scale Out Deployment

Sep 4, 2015

Ive successfully cloned an SSRS VM Server within a scale out deployment to REPLACE a current physical machine. This wasn't too difficult.

The issue im having now is in creating a new SQL 2014 Environment with 3 SSRS nodes. Ive taken the time to build one up. Changed all my config files, installed all components etc & tweaks needed within my company...

I have now hit a brick wall though. Ive cloned this first server twice to give me 3 nodes. This is a new environment so the issue I have is that the rsreportserver.config files all now have the same InstallationID. I dont have any existing nodes to overwrite these files with. So when I attach the nodes to the database they will update the keys table with the same InstallationID as the first node and none will work.

Any way to force the SSRS setup to re-generate an installation ID - by repair maybe? Or is this something I can manually just make up?

View 0 Replies View Related

Transact SQL :: Selecting Rows As Column Name And Other Column Values As Rows

Jun 25, 2015

I have questions and answers from one table, I need to select questions as column names and answers column values as the results for the questions column.

View 28 Replies View Related

Transact SQL :: Recursive Top 100 Rows

Nov 6, 2015

I need limit on recursion. I have a recursion query. which gives me a parent child record set. I want my application to fetch only top 100 rows. In those 100 rows the parent child set should not get break. Even if it gives 105 rows also fine but it should have entire parent child structure.

If you see my below table. where null is the table which dont have parents but have the child.

ITEMID parentItemid
6 NULL
7 NULL
8 6
9 7
12 NULL
13 12
14 8
16 6
17 16

And it is temp table #test1and my recursive query.

;WITH Cte AS
(
SELECT ItemID,ParentItemID,CAST(ItemID AS VARCHAR(200)) [path] FROM #Test1 WHERE ParentItemID IS NULL
UNION ALL
SELECT t.ItemID,t.ParentItemID, CAST([path]+'.'+CAST(t.ItemID AS VARCHAR(20)) AS VARCHAR(200)) FROM Cte c JOIN #Test1 t ON C.ItemID=t.ParentItemID
)
SELECT * FROM Cte ORDER BY path ASC

Here how can i get top 100 parent child set. 

View 4 Replies View Related

Transact SQL :: How To Merge Two Rows Into One Row

Sep 24, 2015

I have a table that has columns like following

trans_code
gl_code
12qw3
a1235
12qw3
a6578
12qw3
t531
e34g6
gt25
e34g6
y7327
e34g6
v23409

Is there an easy way to turn this into format below ??

trans_code
gl_code_1
gl_code_2
12qw3
a1235
a6578
12qw3
a1235

[code]....

View 5 Replies View Related

Transact SQL :: Merging Every 3 Rows Into A Single Row

Aug 18, 2015

I have 2 columns (ID, Msg_text) in a table where i need to combine every 3 rows into single row. What would be the best option i have? I know by using 'STUFF' and 'XML PATH' i can convert all the rows into a single row but here i'm looking for every 3 rows into a single row.

View 3 Replies View Related

Transact SQL :: Convert Rows Into Columns?

Oct 8, 2015

How can I convert the following data

Create Table tbl_Customer_Bank_Details
(
[CustomerID] int,
[CustomerName] varchar(50),
[AccountType] varchar(50),
[BankAccountNo] varchar(50)
)

[Code] ...

into the following format

Create Table tbl_Customer_Bank_Details2
(
[CustomerID] int,
[CustomerName] varchar(50),
[AccountType] varchar(50),
[BankAccountNo1] varchar(50),

[Code] ....

I am looking at this [URL]

how to do this in SQL 2000.

View 16 Replies View Related

Transact SQL :: How To Get Max Date And All Rows Data

Oct 17, 2015

i have this table the TDate in string (not date)

MEN
===
id       |      Name    |      TDate
1        |   aa           |       01.05.2015
2        |   bb           |       05.05.2015

View 6 Replies View Related

Transact SQL :: Combine Two Rows To One Without XML Path

Aug 13, 2015

I have one table list this

declare @test table(Id int, Description varchar(500))
insert into @test
values (1, '<b>Name :</b> XUZ <br/><br/>'),
       (1, '<b>Type : </b> QWE <br /><br/>'),
  (2, '<b>Name : </b> ABC <br /><br/>'),
  (2, '<b>Type : </b> FGH <br /><br/>')

My expected result is 

1, '<b>Name :</b> XUZ <br/><br/> <b>Type : </b> QWE <br /><br/>'
2, '<b>Name : </b> ABC <br /><br/> <b>Type : </b> FGH <br /><br/>'

As you can see its combine two rows of data group by id. Issue is If I use for xml path('') then its replace my html tags <b> to like <b> so after that then I again i need to replace all these symbols. Is it possible to get expected result without using xml path or if we use xml path then still my html tag leave as it is.

View 5 Replies View Related

Transact SQL :: Convert Rows To Columns?

Apr 24, 2015

i have a table with dob and test results , i am trying to pull the data from the table and converting rows columns , below is the table i am using . i used to pivot to do this .

create table #TEST_RESULTS
(ID INT,NAME VARCHAR(10),DOB DATETIME,DAYS_SINCE_BIRTH_TO_TEST INT,TEST_RESULTS INT )
INSERT INTO #TEST_RESULTS
VALUES(1,'A','2015-01-01' , 0 ,1)
,(1,'A','2015-01-01' , 0 ,1)
,(1,'A','2015-01-01' , 1 ,3)
,(1,'A','2015-01-01' , 2 ,6)

[code]...

View 9 Replies View Related

Transact SQL :: How To Compare Rows With Spaces

Nov 17, 2015

I would like to compare rows from 2 tables.

For ex:

Table1
Col1 Col2 Col3
1      a     aa
2      b     bb

Table2
Col1 Col2 Col3
1        a   aa
2      b     bb

Notice Table2.Col2 first row has an extra space " a", where Table1.Col2 value is "a".I need to compare all the columns, not just 1 column (any of the column can be different). Do we use CHECKSUM for this, or is there a better way to compare the 2 tables (in this case resulted in Table2 row 1 col 2 being the difference ?

View 10 Replies View Related

Transact SQL :: Concatenate Description In 2 Rows

Oct 7, 2015

 I have a requirement .Where i might have multiple rows one of the row will have description and second row might be related description but wiht routning number null .I want to concatenate these rows

Id
Routingnum
Ddesc
1
101
A

[code]....

View 8 Replies View Related

Transact SQL :: How To Retrieve Affected Rows

Aug 31, 2015

I have a database table where upon inserting a new record, I get 1 row(s) affected twice. But when deleting the record, I only get one instance of that message. I'm not really an expert, neither have I designed the database, but how can I retrieve the actual affected rows or determine what table does the other row pertain to?

View 2 Replies View Related

Transact SQL :: SUM Of Multiple Rows With Where And Group By

Apr 30, 2015

I have a table Transaction that looks something like the following :

TransactionID          

Currency        Credit             Debit
1     USD      500               0
2     Afcu          6000              0

[Code] ....

I write query like this

select SUM(credit)-SUM(Debit)as [Balance] ,Source from Transaction group by Source

And it came like

Balance Source           
1500                        USD
6000                        Afcu
6800                        INR
7000                        Pfc
-200                         AUD

But I also want to add  Afcu , Pfc with USD and  want output like

Balance Source
14500                        USD
6800                          INR
-200                           AUD

View 3 Replies View Related

Transact SQL :: Find Combination Of Rows?

May 10, 2015

I have this data as below. I need to find out the combination from the data and take a count of them

CREATE TABLE A
(    nRef INT,
     nOrd     INT,
     Token     INT,
     nML              INT,
     nNode            INT,
 sSymbol          VARCHAR(50),
 nMessageCode     INT
)
INSERT INTO A
(   nReferenceNumber,nOrderNumber,nTokenNumber,nML,nNode,sSymbol,nMessageCode )
VALUES
(1, 101, 1001,0,2,'SILVER',13073),

[code]....

if you can see, the rows with column nRefNo 1 and 3 are same i.e. with same combination of Symbol viz. Silver and Castorseed. How to get this combination together and then take count of them. Please note i will be dealing with more than 5 million rows.

View 6 Replies View Related

Transact SQL :: Find How Many Rows Replicated

Aug 20, 2015

How Do we find how many ROWS REPLICATED to subscriber at specific interval ?

View 3 Replies View Related

Transact SQL :: How To Number Rows In SELECT

Oct 8, 2015

I have a SELECT statement with multiple JOINs. I want to number the rows returned by this SELECT statement. What's the easiest way to do this?

My current SELECT statement returns this:

ProjectId -- TaskId -- TaskName
123  - 111 -- Do something
123  - 222 -- Do something else
123  - 333 -- Do one more thing

I want to return this:

ProjectId -- TaskId -- TaskName -- Sequence
123  - 111 -- Do something  -- 1
123  - 222 -- Do something else  -- 2
123  - 333 -- Do one more thing  -- 3

View 2 Replies View Related

Transact SQL :: Where Condition - If No Input Value Select All Rows

Apr 27, 2015

I  have table with filed

EmpProject -Table
Empno, Name, Project NO, cost center

I need to restrict the results by project No by user input. In case if user did not provide any value for the projectNO, then need to fetch all rows.

Select empno, name, projecno, cost_center from empproject where projectno=nvl(:pno, :deptno)

View 6 Replies View Related

Transact SQL :: Add Group Number To Similar Rows?

Jun 9, 2015

How can I add a group number to the following query?

For example, I want to be able to have all rows that have Category = 'Field Sales' and Division = 'CA BDM' to be given a unique group number (GN):

RN                   ReportDate Category                       Division                       TotalBalance
-------------------- ---------- ------------------------------ ------------------------------ ---------------------
1                    2015-06-08 Field Sales                    CA BDM                         299743154.3912
2                    2015-06-07 Field Sales                    CA BDM                         299765954.0354
3                    2015-06-01 Field Sales                    CA BDM                         297902654.4172
1                    2015-06-08 Key Accounts                   Life Office                    49954981.74
2                    2015-06-07 Key Accounts                   Life Office                    50016989.22
3                    2015-06-01 Key Accounts                   Life Office                    50169967.26
4                    2015-05-31 Key Accounts                   Life Office                    50169918.01

Becomes

GN   RN                   ReportDate Category                       Division                TotalBalance
-------------------------- ---------- ------------------------------ ------------------------------ ---------------------
1      1                    2015-06-08 Field Sales                    CA BDM                     299743154.3912
1      2                    2015-06-07 Field Sales                    CA BDM                     299765954.0354
1      3                    2015-06-01 Field Sales                    CA BDM                     297902654.4172
2      1                    2015-06-08 Key Accounts                   Life Office                    49954981.74
2      2                    2015-06-07 Key Accounts                   Life Office                    50016989.22
2      3                    2015-06-01 Key Accounts                   Life Office                    50169967.26
2      4                    2015-05-31 Key Accounts                   Life Office                    50169918.01

i.e. each combination of Category+Division results in a new GN.

The query is:

selectROW_NUMBER() over (partition by Category, Division order by ReportDate desc) 'RN'
, ReportDate
, Category
, Division
, sum(BalanceGBP) as 'TotalBalance'
FROM FlowsAndOpenings
group by ReportDate, Category, Division
order by Category, Division, RN

View 2 Replies View Related

Transact SQL :: Bulk Insert 0 Rows Affected

May 15, 2015

I have a file which has some wind data that i am trying to import into a sql data base through bulk insert. if the script works as it supposed i should see 144 rows impacted but i see 0 rows affected. 

BULK INSERT TOWER.RAWINTERFACE_1058 FROM 'C:Temp900020150427583.txt' 
WITH(CHECK_CONSTRAINTS,CODEPAGE='RAW',DATAFILETYPE='char',FIELDTERMINATOR=' ',ROWTERMINATOR='
',FIRSTROW=172)

The code works if the file is large but if its small 0 rows are affected. and also if i remove the header rows then the file works again. want to understand what is going on here. i am including the screen shot of the file in notepad++. I have tried changing the row terminator to ' ' , ' ' and also tried to change the codepage but nothing seems to work. No error file is being generated either, if i give a error file option. 

View 7 Replies View Related







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