Showing posts with label below. Show all posts
Showing posts with label below. Show all posts

Thursday, March 29, 2012

Create and then USE a dynamically-named database?

I have a need to create a database, and then populate it. However, the
code below doesn't work as I hoped it might (it creates the table in
the "master" database, which is Not A Good Thing). I know already
(thanks Tony!) that if you use Dynamic SQL for the USE command, then
the subsequent operations need to be Dynamic SQL as well, which is a
pity since there are over 11,000 lines of it and I don't really fancy
debugging it!

Does anyone have a cunning plan? In a nutshell, I would like to be
able to:

1. Create a new database with a derived name - as in the case below a
name based on the year, though it might be month as well.

2. Create and populate tables in this new database.

These operations would ideally be running from a scheduled job.

Any thoughts?

TIA

Edward

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

USE MASTER

DECLARE @.DBName VARCHAR(123)

SET @.DBName = 'MyTest_' + CAST((Year(Getdate())) AS Varchar)

if not exists(select dbid from master.dbo.sysdatabases where name =
@.DBName)

exec('CREATE DATABASE ' + @.DBName)

else

raiserror('Database already exists.',3, 1)

EXEC ('USE ' + @.DBName)

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

CREATE TABLE [dbo].[TestTable] (
[TestID] [int] NOT NULL ,
[Description] [varchar] (50) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]
GO

Quote:

Originally Posted by

Does anyone have a cunning plan? In a nutshell, I would like to be
able to:
>
1. Create a new database with a derived name - as in the case below a
name based on the year, though it might be month as well.
>
2. Create and populate tables in this new database.
>


Well, if you are creating databases on the fly then there is probably
some aspect of your design which needs to be relooked.

Basically the USE clause is only in effect for as long as the EXEC
procedure is in scope, so you'll need to place all the statements in
the EXEC procedure, but I would rather recommend you pop this into a
stored procedure in a static database and simply pass the stored
procedure and the DBName as a parameter , e.g.: EXEC('sp_dostuff ' +
@.DBName). Anyway, here's how could've done it. Hope this helps:

USE MASTER

DECLARE @.DBName VARCHAR(123)

SET @.DBName = 'MyTest_' + CAST((Year(Getdate())) AS Varchar)

if not exists(select dbid from master.dbo.sysdatabases where name =
@.DBName)

exec('CREATE DATABASE ' + @.DBName)

else

raiserror('Database already exists.',3, 1)

EXEC ('USE ' + @.DBName +

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

'CREATE TABLE [dbo].[TestTable] ( ' +
' [TestID] [int] NOT NULL , ' +
' [Description] [varchar] (50) COLLATE Latin1_General_CI_AS NULL
' +
') ON [PRIMARY] '
)

Regards,
Louis|||louisyoung187@.hotmail.com wrote:

Quote:

Originally Posted by

Quote:

Originally Posted by

Does anyone have a cunning plan? In a nutshell, I would like to be
able to:

1. Create a new database with a derived name - as in the case below a
name based on the year, though it might be month as well.

2. Create and populate tables in this new database.


>
>
Well, if you are creating databases on the fly then there is probably
some aspect of your design which needs to be relooked.
>
Basically the USE clause is only in effect for as long as the EXEC
procedure is in scope, so you'll need to place all the statements in
the EXEC procedure, but I would rather recommend you pop this into a
stored procedure in a static database and simply pass the stored
procedure and the DBName as a parameter , e.g.: EXEC('sp_dostuff ' +
@.DBName). Anyway, here's how could've done it. Hope this helps:
>
USE MASTER
>
>
DECLARE @.DBName VARCHAR(123)
>
>
SET @.DBName = 'MyTest_' + CAST((Year(Getdate())) AS Varchar)
>
>
if not exists(select dbid from master.dbo.sysdatabases where name =
@.DBName)
>
>
exec('CREATE DATABASE ' + @.DBName)
>
>
else
>
>
raiserror('Database already exists.',3, 1)
>
>
EXEC ('USE ' + @.DBName +
>
>
' if exists (select * from dbo.sysobjects where id = ' +
'object_id(N''[dbo].[TestTable]'') and OBJECTPROPERTY(id,
N''IsUserTable'') ' +
'= 1) ' +
'drop table [dbo].[TestTable] ' +
>
>
>
'CREATE TABLE [dbo].[TestTable] ( ' +
' [TestID] [int] NOT NULL , ' +
' [Description] [varchar] (50) COLLATE Latin1_General_CI_AS NULL
' +
') ON [PRIMARY] '
)
>


Thanks Louis. I know your solution will work, but my script has
11,000+ lines and trying to get that to parse and run in Dynamic SQL is
not on. In conclusion, I don't think this is a candidate for an
automated job so I'll tell the client that I'll create the archive
manually, or give them the tools to do it.

Thanks

Edward|||teddysnips@.hotmail.com wrote:

Quote:

Originally Posted by

louisyoung187@.hotmail.com wrote:

Quote:

Originally Posted by

Quote:

Originally Posted by

Does anyone have a cunning plan? In a nutshell, I would like to be
able to:
>
1. Create a new database with a derived name - as in the case below a
name based on the year, though it might be month as well.
>
2. Create and populate tables in this new database.
>


Well, if you are creating databases on the fly then there is probably
some aspect of your design which needs to be relooked.

Basically the USE clause is only in effect for as long as the EXEC
procedure is in scope, so you'll need to place all the statements in
the EXEC procedure, but I would rather recommend you pop this into a
stored procedure in a static database and simply pass the stored
procedure and the DBName as a parameter , e.g.: EXEC('sp_dostuff ' +
@.DBName). Anyway, here's how could've done it. Hope this helps:

USE MASTER

DECLARE @.DBName VARCHAR(123)

SET @.DBName = 'MyTest_' + CAST((Year(Getdate())) AS Varchar)

if not exists(select dbid from master.dbo.sysdatabases where name =
@.DBName)

exec('CREATE DATABASE ' + @.DBName)

else

raiserror('Database already exists.',3, 1)

EXEC ('USE ' + @.DBName +

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

'CREATE TABLE [dbo].[TestTable] ( ' +
' [TestID] [int] NOT NULL , ' +
' [Description] [varchar] (50) COLLATE Latin1_General_CI_AS NULL
' +
') ON [PRIMARY] '
)


>
Thanks Louis. I know your solution will work, but my script has
11,000+ lines and trying to get that to parse and run in Dynamic SQL is
not on. In conclusion, I don't think this is a candidate for an
automated job so I'll tell the client that I'll create the archive
manually, or give them the tools to do it.
>
Thanks
>
Edward


If this is always happening on a particular instance, could you break
your script down into 4 or 5 steps of an SQL job? Then, after creating
your new DB, you'd just sp_update_jobstep the steps to point to the new
database and then start it? (If multiple runs are possible, you'd also
need to have some way of locking until the job has finished. If always
started from the same DB, then an applock would work)

If the above doesn't help, then some more clues about whether we're
talking about 1, or n, or an unlimited number of instances and/or
databases (from which you kick this process off), or whether you're
kicking this process off through some other means - is it a stored
proc, and job, etc?

Damien

CREATE an INDEX when using CREATE TABLE?

Is there a way to create a index with create table when it is not a primary
key or unique?
Please see below, to see where I am getting lost.
I can create the index using the code below, but I can not see how to create
the index using CREATE TABLE.
drop table customer
-- Customer Table
CREATE TABLE customer
( personID int not null,
userID varchar(10) null
-- cust_userID_ind NONCLUSTERED (userid)
-- CONSTRAINT cust_userID_ind NONCLUSTERED (userid)
,
since smalldatetime not null,
notes varchar(1000) null,
lastupdate smalldatetime not null,
updateby varchar(10) not null,
CONSTRAINT PK_cust_personID PRIMARY KEY CLUSTERED(personID),
-- CONSTRAINT cust_userID_ind NONCLUSTERED (userid),
CONSTRAINT FK_cust_personID FOREIGN KEY (personID) REFERENCES
person(personID),
CONSTRAINT FK_cust_updateby FOREIGN KEY (updateby) REFERENCES
users(userID)
)
go
CREATE INDEX cust_userID_ind
ON customer (userID)
goHi,
Only the Indexes created based on the constraints (PRIMARY AND UNIQUE) will
be created using a
Create Table command.
Other Indexes needs to be created using CREATE INDEX command.
Thanks
Hari
SQL Server MVP
"DazedAndConfused" <AceMagoo61@.yahoo.com> wrote in message
news:uHs5M65uFHA.2312@.TK2MSFTNGP14.phx.gbl...
> Is there a way to create a index with create table when it is not a
> primary key or unique?
> Please see below, to see where I am getting lost.
> I can create the index using the code below, but I can not see how to
> create the index using CREATE TABLE.
> drop table customer
> -- Customer Table
> CREATE TABLE customer
> ( personID int not null,
> userID varchar(10) null
> -- cust_userID_ind NONCLUSTERED (userid)
> -- CONSTRAINT cust_userID_ind NONCLUSTERED (userid)
> ,
> since smalldatetime not null,
> notes varchar(1000) null,
> lastupdate smalldatetime not null,
> updateby varchar(10) not null,
> CONSTRAINT PK_cust_personID PRIMARY KEY CLUSTERED(personID),
> -- CONSTRAINT cust_userID_ind NONCLUSTERED (userid),
> CONSTRAINT FK_cust_personID FOREIGN KEY (personID) REFERENCES
> person(personID),
> CONSTRAINT FK_cust_updateby FOREIGN KEY (updateby) REFERENCES
> users(userID)
> )
> go
> CREATE INDEX cust_userID_ind
> ON customer (userID)
> go
>|||Thank you
"Hari Pra" <hari_pra_k@.hotmail.com> wrote in message
news:uWYaqA6uFHA.740@.TK2MSFTNGP10.phx.gbl...
> Hi,
> Only the Indexes created based on the constraints (PRIMARY AND UNIQUE)
> will be created using a
> Create Table command.
> Other Indexes needs to be created using CREATE INDEX command.
> Thanks
> Hari
> SQL Server MVP
> "DazedAndConfused" <AceMagoo61@.yahoo.com> wrote in message
> news:uHs5M65uFHA.2312@.TK2MSFTNGP14.phx.gbl...
>

Create a View Command in Query Analyzer

Hey...a simple question that I forgot...
May I know how to create a view under Query Analyzer...below is what i have
type, but command succesfully, but view not created...wonder why ?
CREATE VIEW dbo.VIEW1
AS
SELECT * FROM Table1If the command was executed successfull the view was created unless you
didnt turn on something like SET Parseonly etc. Did youdirectly Select from
the row after it was created ? "Select * from View1"
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
" A_PK" <pk999@.hotmail.com> schrieb im Newsbeitrag
news:uayvjYPXFHA.2740@.TK2MSFTNGP14.phx.gbl...
> Hey...a simple question that I forgot...
> May I know how to create a view under Query Analyzer...below is what i
> have type, but command succesfully, but view not created...wonder why ?
> CREATE VIEW dbo.VIEW1
> AS
> SELECT * FROM Table1
>|||but I tried to go to Enterprise Manager, SQL Server, mydatabase, then under
the VIEWS there...
i click...the newly created View1 is not shown there, but I am able to
Select * from View1...
May I know how to make my View1 to be able to see from the enterprise
manager.
thank you
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:OfrB4bPXFHA.3176@.TK2MSFTNGP12.phx.gbl...
> If the command was executed successfull the view was created unless you
> didnt turn on something like SET Parseonly etc. Did youdirectly Select
> from the row after it was created ? "Select * from View1"
> --
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
> " A_PK" <pk999@.hotmail.com> schrieb im Newsbeitrag
> news:uayvjYPXFHA.2740@.TK2MSFTNGP14.phx.gbl...
>|||The gui not always refreshs the right way, did you right click on the View
node and selected Refresh ? That should do it if you placed it in the right
database. Perhaps you issued the command in the wrong database ? Just proof
It via Select @.@.servername,DB_NAME().
If the view was created it should appear in the INFORMATION_SCHEMA:
Select * from INFORMATION_SCHEMA.Tables
Where TABLE_NAME LIKE 'View1'
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
" A_PK" <pk999@.hotmail.com> schrieb im Newsbeitrag
news:OAKfHkPXFHA.2540@.tk2msftngp13.phx.gbl...
> but I tried to go to Enterprise Manager, SQL Server, mydatabase, then
> under the VIEWS there...
> i click...the newly created View1 is not shown there, but I am able to
> Select * from View1...
> May I know how to make my View1 to be able to see from the enterprise
> manager.
> thank you
> "Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in message news:OfrB4bPXFHA.3176@.TK2MSFTNGP12.phx.gbl...
>|||YES, Jens...I am done with that...
Just wonder how could I delete a view then ?
thanks you
"Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote in
message news:OfrB4bPXFHA.3176@.TK2MSFTNGP12.phx.gbl...
> If the command was executed successfull the view was created unless you
> didnt turn on something like SET Parseonly etc. Did youdirectly Select
> from the row after it was created ? "Select * from View1"
> --
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
> " A_PK" <pk999@.hotmail.com> schrieb im Newsbeitrag
> news:uayvjYPXFHA.2740@.TK2MSFTNGP14.phx.gbl...
>|||Hi,
I have a suggestion here.
Do you have dbo right to view all objects?
Since you have created it using dbo, I am not sure whether you are using dbo
right to view the VIEW1.
another thing is, you can check BOL on how to drop a view.
Syntax
DROP VIEW { view } [ ,...n ]
thanks.
Leo Leong|||Drop View [Viewname]
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
" A_PK" <pk999@.hotmail.com> schrieb im Newsbeitrag
news:%23PT391PXFHA.3572@.TK2MSFTNGP12.phx.gbl...
> YES, Jens...I am done with that...
> Just wonder how could I delete a view then ?
> thanks you
> "Jens Smeyer" <Jens@.Remove_this_For_Contacting.sqlserver2005.de> wrote
> in message news:OfrB4bPXFHA.3176@.TK2MSFTNGP12.phx.gbl...
>|||I think you were connected to a different database in Query Analyzer than
you think you were (the one you were looking in in Enterprise Manager). You
can use the Object Search (F4) in Query Analyzer to search for a view called
View1 in all your databases.
Jacco Schalkwijk
SQL Server MVP
" A_PK" <pk999@.hotmail.com> wrote in message
news:uayvjYPXFHA.2740@.TK2MSFTNGP14.phx.gbl...
> Hey...a simple question that I forgot...
> May I know how to create a view under Query Analyzer...below is what i
> have type, but command succesfully, but view not created...wonder why ?
> CREATE VIEW dbo.VIEW1
> AS
> SELECT * FROM Table1
>sql

Sunday, March 25, 2012

Create a sales report

I am using SQL 2000 reporting service. I need to create a sales report
described below.
1. Return the top 10 clients in terms of the sales in Month/Year such as
Sep. 2006.
2. Return the sales to these 10 clients in the past 11 months of the above
entered date such as from Aug. 2005 to Aug. 2006.
3. Line them up to compare the sales in 12 months.
It's very easy to return the top 10 clients. However, I really don't know
how to complete the second retrun. Since the result should be based on the
return of the first query and the result of the first query is dynamic. Is it
possible to have this done in SQL reporting service? I can't find any related
document. Please advice.
Thanks.the Employee Sales Report sample report for Adventureworks does something
very similar to this...The drill down, I think, is either a link or subreport.
--
Wayne Snyder MCDBA, SQL Server MVP
Mariner, Charlotte, NC
I support the Professional Association for SQL Server ( PASS) and it''s
community of SQL Professionals.
"Jun" wrote:
> I am using SQL 2000 reporting service. I need to create a sales report
> described below.
> 1. Return the top 10 clients in terms of the sales in Month/Year such as
> Sep. 2006.
> 2. Return the sales to these 10 clients in the past 11 months of the above
> entered date such as from Aug. 2005 to Aug. 2006.
> 3. Line them up to compare the sales in 12 months.
> It's very easy to return the top 10 clients. However, I really don't know
> how to complete the second retrun. Since the result should be based on the
> return of the first query and the result of the first query is dynamic. Is it
> possible to have this done in SQL reporting service? I can't find any related
> document. Please advice.
> Thanks.

Thursday, March 22, 2012

Create a Letter

hi there,
Anybody know how to create a letter using Sql Reporting. My report
format is given below please advice which tool item i should use and
how to justify the letter body.
where xxx is from database
Dear Mr xxxx
xxxx is pleased to confirm the receipt of the sub amt for the xxx
project. the details of which are as follows
sub for : xxx
all : xxx
two sentence here
please advice how can i do this...
thnxJust drag a list control expand till you get a decent size of the letter and
place various text box's inside, each will be placed as per your letter eg.
some has fixed text and couple of variable textbox eg. Name of the person.
in the properties of the listbox create group and give a page break. in your
case the group will be set on emp name.. so it prints in different page for
each emp.
Amarnath
"Murali" wrote:
> hi there,
> Anybody know how to create a letter using Sql Reporting. My report
> format is given below please advice which tool item i should use and
> how to justify the letter body.
> where xxx is from database
> Dear Mr xxxx
> xxxx is pleased to confirm the receipt of the sub amt for the xxx
> project. the details of which are as follows
> sub for : xxx
> all : xxx
> two sentence here
>
> please advice how can i do this...
> thnx
>

Monday, March 19, 2012

Crass Tab Query

Hi!

I m using sql 2005.I have a table as showing below.

yearRegionloan_amtpur_idpurpose1981Andhra pradesh$20,000.00 1Animal Husbandary1981Arunachal Pradesh$110,000.00 1Animal Husbandary1981Assam$240,000.00 1Animal Husbandary1981Bihar$75,000.00 1Animal Husbandary1981Chhattisgarh$55,500.00 1Animal Husbandary1981Gujarat$77,500.00 1Animal Husbandary1982Goa$44,888.00 1Animal Husbandary1982Himachal pradesh$4,000.00 1Animal Husbandary1982Himachal pradesh$20,000.00 1Animal Husbandary1982Jammu and kashmir$30,000.00 1Animal Husbandary1882Jharkhand$35,000.00 1Animal Husbandary1982Karnataka$40,000.00 1Animal Husbandary1982Kerala $20,000.00 1Animal Husbandary1982Madhya pradesh$5,000.00 1Animal Husbandary

I want to produce report as by using crosstab query as showing bellow

Year Asam Hyadrabad goa arunachal pardesh etc.........

1981 1000.00 2000.00 8000.2 00000 000000 .....

1981

'

'

Is it possible by crosstab query ?or please suggest me another way as early as possible.

Thanx in advance.

Abhishek

http://www.databasejournal.com/features/mssql/article.php/10894_3516331_2

Cr9.0

in my pageheader , got country and cityname.
below it, is a section that has district as a group.
below it, is detail section with game field in it.
query:
select country, CityName, district,
case when (population > 200) then game else null end
from country, province, city
group CityName, district
my problem is how to suppress the page header when game is null.You can conditionaly suppress your Page Header (or a PH section).
In the Section Expert, check the Suppress option for your PageHeader, click the 'x+2' button and print such a formula:

Count({table.game},{table.district})=0

Sunday, March 11, 2012

CR & LF Problems

I'm trying to concatenate three address fields into one for a SELECT
statement. Below is that part:
CASE WHEN ADDR1 IS NULL
THEN ''
ELSE ADDR1 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR2 IS NULL
THEN ''
ELSE ADDR2 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR3 IS NULL
THEN ''
ELSE ADDR3
END AS Address,
But the results do not have the CR and LF in it. What am I doing
wrong?I don't see a problem here:
create table #tmp (addr1 varchar(20), addr2 varchar(20), addr3 varchar(20))
insert #tmp values ('line 1 field 1', 'line 1 field 2', 'line 1 field 3')
insert #tmp values ('line 2 field 1', 'line 2 field 2', NULL)
insert #tmp values (NULL, 'line 3 field 2', NULL)
SELECT
CASE WHEN ADDR1 IS NULL
THEN ''
ELSE ADDR1 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR2 IS NULL
THEN ''
ELSE ADDR2 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR3 IS NULL
THEN ''
ELSE ADDR3
END AS Address
FROM #tmp
output:
Address
---
line 1 field 1
line 1 field 2
line 1 field 3
line 2 field 1
line 2 field 2
line 3 field 2
P.S. It sure woulda been nice if you had taken the time to construct the
demo code I did! :-))
TheSQLGuru
President
Indicium Resources, Inc.
"Paul" <pwh777@.hotmail.com> wrote in message
news:1178224810.009904.225630@.h2g2000hsg.googlegroups.com...
> I'm trying to concatenate three address fields into one for a SELECT
> statement. Below is that part:
> CASE WHEN ADDR1 IS NULL
> THEN ''
> ELSE ADDR1 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR2 IS NULL
> THEN ''
> ELSE ADDR2 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR3 IS NULL
> THEN ''
> ELSE ADDR3
> END AS Address,
> But the results do not have the CR and LF in it. What am I doing
> wrong?
>|||Paul,
If you run this query to return results in a grid in Query Analyzer or the
Management Studio Query editor (depending on version of SQL) the results
appear in a single cell. But if your results return as text you will see
the line breaks.
RLF
"Paul" <pwh777@.hotmail.com> wrote in message
news:1178224810.009904.225630@.h2g2000hsg.googlegroups.com...
> I'm trying to concatenate three address fields into one for a SELECT
> statement. Below is that part:
> CASE WHEN ADDR1 IS NULL
> THEN ''
> ELSE ADDR1 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR2 IS NULL
> THEN ''
> ELSE ADDR2 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR3 IS NULL
> THEN ''
> ELSE ADDR3
> END AS Address,
> But the results do not have the CR and LF in it. What am I doing
> wrong?
>

CR & LF Problems

I'm trying to concatenate three address fields into one for a SELECT
statement. Below is that part:
CASE WHEN ADDR1 IS NULL
THEN ''
ELSE ADDR1 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR2 IS NULL
THEN ''
ELSE ADDR2 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR3 IS NULL
THEN ''
ELSE ADDR3
END AS Address,
But the results do not have the CR and LF in it. What am I doing
wrong?
I don't see a problem here:
create table #tmp (addr1 varchar(20), addr2 varchar(20), addr3 varchar(20))
insert #tmp values ('line 1 field 1', 'line 1 field 2', 'line 1 field 3')
insert #tmp values ('line 2 field 1', 'line 2 field 2', NULL)
insert #tmp values (NULL, 'line 3 field 2', NULL)
SELECT
CASE WHEN ADDR1 IS NULL
THEN ''
ELSE ADDR1 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR2 IS NULL
THEN ''
ELSE ADDR2 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR3 IS NULL
THEN ''
ELSE ADDR3
END AS Address
FROM #tmp
output:
Address
line 1 field 1
line 1 field 2
line 1 field 3
line 2 field 1
line 2 field 2
line 3 field 2
P.S. It sure woulda been nice if you had taken the time to construct the
demo code I did! :-))
TheSQLGuru
President
Indicium Resources, Inc.
"Paul" <pwh777@.hotmail.com> wrote in message
news:1178224810.009904.225630@.h2g2000hsg.googlegro ups.com...
> I'm trying to concatenate three address fields into one for a SELECT
> statement. Below is that part:
> CASE WHEN ADDR1 IS NULL
> THEN ''
> ELSE ADDR1 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR2 IS NULL
> THEN ''
> ELSE ADDR2 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR3 IS NULL
> THEN ''
> ELSE ADDR3
> END AS Address,
> But the results do not have the CR and LF in it. What am I doing
> wrong?
>
|||Paul,
If you run this query to return results in a grid in Query Analyzer or the
Management Studio Query editor (depending on version of SQL) the results
appear in a single cell. But if your results return as text you will see
the line breaks.
RLF
"Paul" <pwh777@.hotmail.com> wrote in message
news:1178224810.009904.225630@.h2g2000hsg.googlegro ups.com...
> I'm trying to concatenate three address fields into one for a SELECT
> statement. Below is that part:
> CASE WHEN ADDR1 IS NULL
> THEN ''
> ELSE ADDR1 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR2 IS NULL
> THEN ''
> ELSE ADDR2 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR3 IS NULL
> THEN ''
> ELSE ADDR3
> END AS Address,
> But the results do not have the CR and LF in it. What am I doing
> wrong?
>

CR & LF Problems

I'm trying to concatenate three address fields into one for a SELECT
statement. Below is that part:
CASE WHEN ADDR1 IS NULL
THEN ''
ELSE ADDR1 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR2 IS NULL
THEN ''
ELSE ADDR2 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR3 IS NULL
THEN ''
ELSE ADDR3
END AS Address,
But the results do not have the CR and LF in it. What am I doing
wrong?I don't see a problem here:
create table #tmp (addr1 varchar(20), addr2 varchar(20), addr3 varchar(20))
insert #tmp values ('line 1 field 1', 'line 1 field 2', 'line 1 field 3')
insert #tmp values ('line 2 field 1', 'line 2 field 2', NULL)
insert #tmp values (NULL, 'line 3 field 2', NULL)
SELECT
CASE WHEN ADDR1 IS NULL
THEN ''
ELSE ADDR1 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR2 IS NULL
THEN ''
ELSE ADDR2 + CHAR(13) + CHAR(10)
END +
CASE WHEN ADDR3 IS NULL
THEN ''
ELSE ADDR3
END AS Address
FROM #tmp
output:
Address
---
line 1 field 1
line 1 field 2
line 1 field 3
line 2 field 1
line 2 field 2
line 3 field 2
P.S. It sure woulda been nice if you had taken the time to construct the
demo code I did! :-))
--
TheSQLGuru
President
Indicium Resources, Inc.
"Paul" <pwh777@.hotmail.com> wrote in message
news:1178224810.009904.225630@.h2g2000hsg.googlegroups.com...
> I'm trying to concatenate three address fields into one for a SELECT
> statement. Below is that part:
> CASE WHEN ADDR1 IS NULL
> THEN ''
> ELSE ADDR1 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR2 IS NULL
> THEN ''
> ELSE ADDR2 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR3 IS NULL
> THEN ''
> ELSE ADDR3
> END AS Address,
> But the results do not have the CR and LF in it. What am I doing
> wrong?
>|||Paul,
If you run this query to return results in a grid in Query Analyzer or the
Management Studio Query editor (depending on version of SQL) the results
appear in a single cell. But if your results return as text you will see
the line breaks.
RLF
"Paul" <pwh777@.hotmail.com> wrote in message
news:1178224810.009904.225630@.h2g2000hsg.googlegroups.com...
> I'm trying to concatenate three address fields into one for a SELECT
> statement. Below is that part:
> CASE WHEN ADDR1 IS NULL
> THEN ''
> ELSE ADDR1 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR2 IS NULL
> THEN ''
> ELSE ADDR2 + CHAR(13) + CHAR(10)
> END +
> CASE WHEN ADDR3 IS NULL
> THEN ''
> ELSE ADDR3
> END AS Address,
> But the results do not have the CR and LF in it. What am I doing
> wrong?
>

Friday, February 24, 2012

coupla sql questions

say i have this file (below) and want to enter it into a table i've made. why cant i do this in query analyzer? and whats the easiest/best way to do it

insert into myTable

values(1,"StaticHtml","StaticHtmlPageControl"
2,"Questions","QuestionsPageControl"
3,"Login","LoginPageControl"
4,"SubmitSurvey","SubmitSurveyPageControl"
5,"Registration","RegistrationPageControl"
7,"SubmitUserAttributesSurvey","SubmitUserAttributesSurveyControl"
10,"RepeatPageGroup","RepeatPage"
11,"ThankYouPage","ThankYouPageControl")

also

whats the easiest way to make a copy of a database with and without the data - on the same server

cheers

Your SQL syntax isn't quite right. You'll need to write an INSERT INTO for each row you want to insert. i.e.

INSERT INTO myTable VALUES(1,"StaticHtml","StaticHtmlPageControl")

INSERT INTO myTable VALUES(2,"Questions","QuestionsPageControl")

You can script the database structure in order to create a blank instance of your database - Enterprise Manager / SQL Management Studio has options for this. To "copy" your database including data, you should take a backup.

|||

Thx man

bit annoying how u have to write insert into for each row, especially if there's heaps of rows.. i was hoping there might have been a better/easier way

i was also hoping you could copy a database like a table eg: select * into db1 from db2 - or something similar

anyway, i'll just keep hoping

cheers

|||

If you're selecting data from one table into another, you can do multiple rows - like this

INSERT INTO tblTable1
SELECT * FROM tblTable2

If the fields don't match, just specify the columns:

INSERT INTO tblTable1 (Field1, Field2, Field3)
SELECT FieldA, FieldB, FieldC FROM tblTable2

Sunday, February 19, 2012

Counts by groups

I expect to get a record below with a count of 0 (and I do), but when I take the comments out (--) of lines 1 & 6 I don't understand why I get no records at all. I need to be able to see all teams in EvalAnswers even if none of the records satisfies the where clause.

1select Count(*)as cnt--, TeamID2from EvalAnswers3where CoID=@.CoID4and EvaluatorID=@.EvaluatorID5and (Scr0=0 and Sugg0is NULL)6--group by TeamID7

BBradshaw:

even if none of the records satisfies the where clause.

- Why have the where clause then? A "Where" clause (as you know) filters out anything that doesn't match it... so what do you really want.. please explain what you are trying to query in human terms, not code terms, and I can help you better.

Thanks,

|||

Obviously, as shown by the commented-out query, SQL is designed to return a count of zero to tell me none of a specific filtered/matching kind of record currently exists, which is exactly what I want. I now want to show an itemized listing of all teams within a given company with their counts of existing filtered/matching records for each,even/especially if none exists. I know I can use the ALL construct on my Group By clause to get the zero counts for non-matching records, but that seems to give me too much (all companies, not just the one specified).

So, this morning I plan to play with the ALL and HAVING clauses, and expect to get what I need that way. However, I may be going about this all wrong, so any help would be appreciated.

|||

Please let me know if you see anything wrong with this code. It seems to work correctly for what I want, but I've tested in on only one scenario. I think the ALL and HAVING worked, rearranging the other parameters.

I appreciate your comments and help.

1selectCoID, TeamID, Count(*)as incomplete2fromEvalAnswers3whereScr0=0 and Sugg0is NULL4group byallCoID, TeamID, EvaluatorID5 havingCoID=@.CoID and EvaluatorID=@.EvaluatorID
|||I'm glad to see you've found the right way, you really need GROUP BY ALL in this case. This is why we need "GROUP BY ALL", it's by design, not a flaw of T-SQL.

Friday, February 17, 2012

Counting Question

Below is what I currently have in query. I have a question for the line tha
t
has an asterisk before it.
Is there a way to show if a card number has shown up more than once on a
given settlement _batch_num? I have no clue what to put as the COUNT CASE
since I am searching over a period of settlement_batch_num's. I just need
cards that duplicate only on the same settlement_batch_num. Is there anyway
to list the card also? The settlement_batch_num is a certain day. Thanks
for any help.
Use Winpayment
GO
SELECT S.card_acceptor_identification STORE,
COUNT (M.message_type) TOTAL_#_TRANS,
COUNT(CASE WHEN id_code_1 = 'DB' and response_code <> '00' THEN 1 END)
DEBIT_DECLINED
*COUNT(CASE When card_num = ? and settlement_batch_num = ? )
FROM Store S
Left Join financial_message M
On M.card_acceptor_identification = S.card_acceptor_identification
And (settlement_batch_number >= '867'
And settlement_batch_nunber <= '888')
GROUP BY S.card_acceptor_identificationOn Tue, 24 May 2005 08:48:04 -0700, tarheels4025 wrote:

>Below is what I currently have in query. I have a question for the line th
at
>has an asterisk before it.
>Is there a way to show if a card number has shown up more than once on a
>given settlement _batch_num? I have no clue what to put as the COUNT CASE
>since I am searching over a period of settlement_batch_num's. I just need
>cards that duplicate only on the same settlement_batch_num. Is there anywa
y
>to list the card also? The settlement_batch_num is a certain day. Thanks
>for any help.
(snip)
Hi tarheels,
Since you're not exactly new to this group, you probably won't be
surprised to be pointed to www.aspfaq.com/5006.
From your description, I *THINK* that it's possible to do what you want
to do - but I also *KNOW* that I don't really understand your exact
requirements.
Post table structure, sample data and expected output (as indicated on
www.aspfaq.com/5006), then we'll be able to help you.
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Counting Occurences

I'm having trouble getting my head around this, and no one in the groups
has posted exactly the problem.

The table below tracks site traffic across a network. There is 1 row
per pageview and UUID is that user's unique cookie.

CREATE TABLE [dbo].[Stats_Working] (
[inac_stats_id] [int] NOT NULL ,
[hit_time] [datetime] NULL ,
[site_id] [int] NULL ,
[site_cat_id] [int] NULL ,
[item_id] [int] NULL ,
[local_content_cat_id] [int] NULL ,
[UUID] [float] NULL ,
[USER_AGENT] [char] (50) NULL
) ON [PRIMARY]
GO

A client asked: of these pageviews and within each category, how many
are accounted for by users that generated 2 or fewer pageviews, 3+
pageviews, and 4+ pageviews?

I said, "yes, we have that information". I know it's here, but I'm
braindead from looking at what should be a simple solution.

Thanks for any help
Cam Bevis

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!Cam Bevis (anonymous@.devdex.com) writes:
> I'm having trouble getting my head around this, and no one in the groups
> has posted exactly the problem.
> The table below tracks site traffic across a network. There is 1 row
> per pageview and UUID is that user's unique cookie.
> CREATE TABLE [dbo].[Stats_Working] (
> [inac_stats_id] [int] NOT NULL ,
> [hit_time] [datetime] NULL ,
> [site_id] [int] NULL ,
> [site_cat_id] [int] NULL ,
> [item_id] [int] NULL ,
> [local_content_cat_id] [int] NULL ,
> [UUID] [float] NULL ,
> [USER_AGENT] [char] (50) NULL
> ) ON [PRIMARY]
> GO
> A client asked: of these pageviews and within each category, how many
> are accounted for by users that generated 2 or fewer pageviews, 3+
> pageviews, and 4+ pageviews?
> I said, "yes, we have that information". I know it's here, but I'm
> braindead from looking at what should be a simple solution.

If I understand this right, and am not too confused at this late hour:

SELECT COUNT(*), no_of_views
FROM (SELECT no_of_views = CASE WHEN cnt <= 2 THEN '<= 2 pagewiews'
WHEN cnt = 3 THEN '= 3 pageviews'
ELSE '>= 4 pageviews'
END
FROM (SELECT cnt, COUNT(*)
FROM Stats_Working
GROUP BY UUID) AS a) AS b
GROUP BY no_of_views

So I am cheating a bit. You don't get 3+ pageviews, but 3 exactly.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Thanks, but not exactly.

What we're trying to return something more like

(pivot this into columns, no room on this editor)

Total Pageviews: 100,000
Pageviews by users that generated 2 or less pageviews:60,000
Pageviews by users that generated 3 or more pageviews:40,000
Pageviews by users that generated 3 or more pageviews:20,000

The trick is counting the occurences of the UUID (unique cookie) in the
table and... select count [distinct?[(uuid)...where count
[distinct?](uuid)<=2,...

something like. I know it's there somewhere.

I guess the goal is best stated as seeing how many pageviews are
generated by people that poke around for a while(or not), and putting
them into groups. It's some kind of metric.

Thanks for your response!

Cam

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Cam Bevis (anonymous@.devdex.com) writes:
> Thanks, but not exactly.
> What we're trying to return something more like
> (pivot this into columns, no room on this editor)
> Total Pageviews: 100,000
> Pageviews by users that generated 2 or less pageviews:60,000
> Pageviews by users that generated 3 or more pageviews:40,000
> Pageviews by users that generated 3 or more pageviews:20,000
>
> The trick is counting the occurences of the UUID (unique cookie) in the
> table and... select count [distinct?[(uuid)...where count
> [distinct?](uuid)<=2,...
> something like. I know it's there somewhere.

It would help if you could provide sample data in form of INSERT statements
and the then desired output from that sample output. That would make it
easier for anyone who tries it to test a solution.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Cam Bevis" wrote:
> I'm having trouble getting my head around this, and no one in the groups
> has posted exactly the problem.
> The table below tracks site traffic across a network. There is 1 row
> per pageview and UUID is that user's unique cookie.
> CREATE TABLE [dbo].[Stats_Working] (
> [inac_stats_id] [int] NOT NULL ,
> [hit_time] [datetime] NULL ,
> [site_id] [int] NULL ,
> [site_cat_id] [int] NULL ,
> [item_id] [int] NULL ,
> [local_content_cat_id] [int] NULL ,
> [UUID] [float] NULL ,
> [USER_AGENT] [char] (50) NULL
> ) ON [PRIMARY]
> GO
> A client asked: of these pageviews and within each category, how many
> are accounted for by users that generated 2 or fewer pageviews, 3+
> pageviews, and 4+ pageviews?
> I said, "yes, we have that information". I know it's here, but I'm
> braindead from looking at what should be a simple solution.

I ignored the "within each category" requirement above, but this should get
you going:

CREATE TABLE [dbo].[Stats_Working] (
[inac_stats_id] [int] NOT NULL ,
[hit_time] [datetime] NULL ,
[site_id] [int] NULL ,
[site_cat_id] [int] NULL ,
[item_id] [int] NULL ,
[local_content_cat_id] [int] NULL ,
[UUID] [float] NULL ,
[USER_AGENT] [char] (50) NULL
) ON [PRIMARY]
GO

insert [Stats_Working] values (0, null, 0, 0, 0, 0, 1.0, '')

insert [Stats_Working] values (0, null, 0, 0, 0, 0, 2.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 2.0, '')

insert [Stats_Working] values (0, null, 0, 0, 0, 0, 3.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 3.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 3.0, '')

insert [Stats_Working] values (0, null, 0, 0, 0, 0, 4.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 4.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 4.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 4.0, '')

insert [Stats_Working] values (0, null, 0, 0, 0, 0, 5.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 5.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 5.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 5.0, '')
insert [Stats_Working] values (0, null, 0, 0, 0, 0, 5.0, '')

select UUID, count(*) as 'hits'
from Stats_working
group by UUID

select sum(case when sub.hits <= 2 then sub.hits else 0 end) '2 or fewer',
sum(case when sub.hits >= 3 then sub.hits else 0 end) '3 or more',
sum(case when sub.hits >= 4 then sub.hits else 0 end) '4 or more'
from (
select UUID, count(*) as 'hits'
from Stats_working
group by UUID
)
AS sub
go

--RESULTS--

UUID hits
-- ---
1.0 1
2.0 2
3.0 3
4.0 4
5.0 5

2 or fewer 3 or more 4 or more
---- ---- ----
3 12 9|||I think a tiny change to Erland's solution might do the trick...

SELECT TotalViews = SUM(cnt), no_of_views
FROM (SELECT cnt, no_of_views = CASE WHEN cnt <= 2 THEN '<= 2 pagewiews'
WHEN cnt = 3 THEN '= 3 pageviews'
ELSE '>= 4 pageviews'
END
FROM (SELECT cnt = COUNT(*)
FROM Stats_Working
GROUP BY UUID) AS a) AS b
GROUP BY no_of_views

So I am cheating a bit. You don't get 3+ pageviews, but 3 exactly.

Counting items

I want to run a select query and also using that items keys get the count of
the items in the inventory db, kinda like this below but does not Parse
SELECT dbo.Pattern.Pattern_ID, dbo.ProductType.ProdType_ID,
dbo.Manufact_Company.ManuComp_ID, XCount AS
(SELECT Count(ID)
FROM wholesaleinv
WHERE Pattern_ID = dbo.Pattern.Pattern_ID
AND ManuComp_ID = dbo.Manufact_Company.ManuComp_ID AND
Prodtype_ID = dbo.PTC2CLEAN.ProdType_ID)
FROM dbo.Pattern INNER JOIN
dbo.PTC2CLEAN ON dbo.Pattern.Pattern_ID =
dbo.PTC2CLEAN.Pattern_ID INNER JOIN
dbo.ProductType ON dbo.PTC2CLEAN.ProdType_ID =
dbo.ProductType.ProdType_ID INNER JOIN
dbo.Manufact_Company ON dbo.PTC2CLEAN.ManuComp_ID =
dbo.Manufact_Company.ManuComp_IDPlease post DDL, sample data and desired results.
See http://www.aspfaq.com/5006 for info.
"TdarTdar" <TdarTdar@.discussions.microsoft.com> wrote in message
news:231CE73E-0716-46C4-A4C4-B7C688023022@.microsoft.com...
>I want to run a select query and also using that items keys get the count
>of
> the items in the inventory db, kinda like this below but does not Parse
> SELECT dbo.Pattern.Pattern_ID, dbo.ProductType.ProdType_ID,
> dbo.Manufact_Company.ManuComp_ID, XCount AS
> (SELECT Count(ID)
> FROM wholesaleinv
> WHERE Pattern_ID = dbo.Pattern.Pattern_ID
> AND ManuComp_ID = dbo.Manufact_Company.ManuComp_ID AND
> Prodtype_ID = dbo.PTC2CLEAN.ProdType_ID)
> FROM dbo.Pattern INNER JOIN
> dbo.PTC2CLEAN ON dbo.Pattern.Pattern_ID =
> dbo.PTC2CLEAN.Pattern_ID INNER JOIN
> dbo.ProductType ON dbo.PTC2CLEAN.ProdType_ID =
> dbo.ProductType.ProdType_ID INNER JOIN
> dbo.Manufact_Company ON dbo.PTC2CLEAN.ManuComp_ID =
> dbo.Manufact_Company.ManuComp_ID|||A quick glance reveals a peculiarity - "..., XCount AS (select..." is wrong.
Replace it with "(select ...) as XCount".
Any other help will be available if you share your DDL with us.
ML

Tuesday, February 14, 2012

counting based on bit flag

I have a table with an id field (int) and a bit flag. example below

id flag

1 true

1 true

1 false

1 true

2 true

2 false

I am looking for a query that will provide me the following results if possible

id true false

1 3 1

2 1 1

Any and all help is appreciated.

My efforts so far aren't worth sharing. I am looking for completely new approaches.

Thanks a ton

Use something like this:

Code Snippet


DECLARE @.MyTable table
( ID int,
Flag smallint
)


INSERT INTO @.MyTable VALUES ( 1, 1 )
INSERT INTO @.MyTable VALUES ( 1, 1 )
INSERT INTO @.MyTable VALUES ( 1, 0 )
INSERT INTO @.MyTable VALUES ( 1, 1 )
INSERT INTO @.MyTable VALUES ( 2, 1 )
INSERT INTO @.MyTable VALUES ( 2, 0 )


SELECT
[ID],
True = sum( CASE Flag WHEN 1 THEN 1 ELSE 0 END ),
False = sum ( CASE Flag WHEN 0 THEN 1 ELSE 0 END )
FROM @.MyTable
GROUP BY [ID]


ID True False
-- -- --
1 3 1
2 1 1

|||Excellent!! Thank you so much!