Showing posts with label column. Show all posts
Showing posts with label column. Show all posts

Friday, March 30, 2012

how to control the table's column number

Hi,

When I add the table into the report, the default column number is 3. Let's say I need 10 columns on the report, besides right click on the last column and click on "add column right" to add the other 7 columns, is there any easy way?

Thanks.

Sorry, there is no other way of doing this. You have to add additional columns through the popup menu.

-- Robert

sql

How to control format of datetime attributes?

There is an attribute that have type DateTime, based on the field type in data source. It hasn't separate name column. The member caption is formatted as yyyy-MM-dd hh:mm:ss. Can I control the format of Member name without giving separate name column.

I assigned different format in the format field of key property window, but it had no effect. What I did wrong?

Hello. I do not think that you will have to pay any penalty from adding a new column in the data source view with a new format of your date column. I recommend to use the TSQL function CONVERT that have arguments for different date formats. Have a look at CONVERT in Books On Line, and you will see the complete list of different codes/arguments for different date formats.

HTH

Thomas Ivarsson

|||

Thank you,

I thought about more sofisticated solution, that can be used in multi culture environment without adding x additional fields with "formatting" of a datetime attribute.

I hoped, that the AS2005 is smarter as AS2005 and offers more possibilties.

Do you know what is the format field in key properties for?

how to control a column limited to display?

Hi,

Can I control a column to displayed to a specifal user or specifal role?

If not the specifal user or specifal role, the column will can not be displayed.

Thank you.

Jeffers

You can set a conditional column visibility using User!UserID. For more involved scenarios, you may need to whip out some code to find the role/group the user belongs to given the user logon name.

Wednesday, March 28, 2012

How to consolidate multiple rows into a single column

Hello,
I would like some help on developing a SQL query.
I have a Team table and a Person Table. For simplicity sake, lets say
the Team has a key and team name. The Person has a person key, team
key, and person name.
I want to query for all team members, and store the results in a single
column. So, the resulting view would have three columns: team key, team
name, and a list of all people on the team.
Any pointers or tips appreciated,
J Wolfgang GoerlichSELECT T.team_key, T.team_name, P.person_name
FROM Team AS T
JOIN Person AS P
ON T.team_key = P.team_key ;
David Portas
SQL Server MVP
--|||Here is a sample:
=====
CREATE TABLE Team
(
TeamID INT,
TeamName VARCHAR(20)
)
GO
CREATE TABLE Person
(
PersonID INT,
TeamID INT,
PersonName VARCHAR(50)
)
GO
INSERT INTO Team VALUES (1, 'Development')
INSERT INTO Team VALUES (2, 'Release')
INSERT INTO Person VALUES (1, 1, 'Bob')
INSERT INTO Person VALUES (2, 1, 'Mason')
INSERT INTO Person VALUES (3, 2, 'Chris')
INSERT INTO Person VALUES (4, 2, 'Scott')
INSERT INTO Person VALUES (5, 2, 'Bruce')
GO
=====
The above just creates some sample tables and data. Now, we can define a
function that concatenates the list of team members as follows:
=====
IF (OBJECT_ID ('dbo.formTeamList') IS NOT NULL)
DROP FUNCTION dbo.formTeamList
GO
CREATE FUNCTION dbo.formTeamList (@.teamID INT)
RETURNS VARCHAR(8000) AS
BEGIN
DECLARE @.teamList VARCHAR(8000); SET @.teamList = ''
SELECT
@.teamList = @.teamList + ', ' + ISNULL (PersonName, '')
FROM
Person
WHERE
TeamID = @.teamID
RETURN (STUFF (@.teamList, 1, 2, ''))
END
GO
=====
Once done, we can test this out as follows:
=====
SELECT
TeamID, TeamName, dbo.formTeamList (TeamID)
FROM
Team
=====
Although the method shown above works, it is not recommended as there are
limitations:
(1) The function is called for every row in the team table. This can cause
performance problems for large lists.
(2) The function can only concatenate a list of 8000 characters in length
(4000 if you are using UniCode).
Such logic is usually best handled in the application tier of your program,
sinnce you have good flexibility to rotate rows into columns.
--
HTH,
SriSamp
Email: srisamp@.gmail.com
Blog: http://blogs.sqlxml.org/srinivassampath
URL: http://www32.brinkster.com/srisamp
<jwgoerlich@.gmail.com> wrote in message
news:1131967790.112616.168370@.g44g2000cwa.googlegroups.com...
> Hello,
> I would like some help on developing a SQL query.
> I have a Team table and a Person Table. For simplicity sake, lets say
> the Team has a key and team name. The Person has a person key, team
> key, and person name.
> I want to query for all team members, and store the results in a single
> column. So, the resulting view would have three columns: team key, team
> name, and a list of all people on the team.
> Any pointers or tips appreciated,
> J Wolfgang Goerlich
>

Monday, March 19, 2012

How to configure multiple subscriber to same publisher using filte

Hi,
I have a base table in publisher db. I have a column, using which i want to
filter it and replicate it to certain dbs. how do i dynamically do it ?
Like for eg, consider this table :
ID Project name center
1 A NY
2 B LON
3 C PAR
now, i want to filter using the column "center". if center = 'NY', then i
must direct it to a particular subscriber. if it is "LON" then it must be
directed to someother subscriber. also, i must accomplish this using merge
replication
for my requirement, i am not able to use multiple publishers to accomplish
it. i must use one publisher, with a filter which varies dynamically
depending on the subscriber.
please explain how i can accomplish this.
PS : I'm new to databases. sorry if this question is very basic
Ki,
this question is not at all basic
You can use dynamic filtering in merge replication. Set up the filter as
center = HOST_NAME(). In the merge agent, before initializing, edit the
command-line parameters and add -HOSTNAME NY for the NY subscriber and so on
for the others.
Rgds,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)

Monday, March 12, 2012

How to configur a column to be unique value from the Enterprize Ma

Hi, I want one of the column in a table to not have duplicate values(it's
Varchar) but it's not the primary key column which is a auto-generated id
column for the table.
Thanks,
AlphaCreate a unique constraint on the column
http://sqlservercode.blogspot.com/
"Alpha" wrote:
> Hi, I want one of the column in a table to not have duplicate values(it's
> Varchar) but it's not the primary key column which is a auto-generated id
> column for the table.
> Thanks,
> Alpha|||Sorry I wasn't clear on my question. I know I need to set the unique
constraint but just didn't know where is Enterprise Manager is the setting.
I just found it now in the design and right click on the column. thanks for
your help anyway.
"SQL" wrote:
> Create a unique constraint on the column
> http://sqlservercode.blogspot.com/
>
> "Alpha" wrote:
> > Hi, I want one of the column in a table to not have duplicate values(it's
> > Varchar) but it's not the primary key column which is a auto-generated id
> > column for the table.
> >
> > Thanks,
> > Alpha

How to configur a column to be unique value from the Enterprize Ma

Hi, I want one of the column in a table to not have duplicate values(it's
Varchar) but it's not the primary key column which is a auto-generated id
column for the table.
Thanks,
Alpha
Create a unique constraint on the column
http://sqlservercode.blogspot.com/
"Alpha" wrote:

> Hi, I want one of the column in a table to not have duplicate values(it's
> Varchar) but it's not the primary key column which is a auto-generated id
> column for the table.
> Thanks,
> Alpha

How to configur a column to be unique value from the Enterprize Ma

Hi, I want one of the column in a table to not have duplicate values(it's
Varchar) but it's not the primary key column which is a auto-generated id
column for the table.
Thanks,
AlphaCreate a unique constraint on the column
http://sqlservercode.blogspot.com/
"Alpha" wrote:

> Hi, I want one of the column in a table to not have duplicate values(it's
> Varchar) but it's not the primary key column which is a auto-generated id
> column for the table.
> Thanks,
> Alpha

Friday, March 9, 2012

How to concatenate two text columns

Hi all,
I have a two text columns in my table with more than 100,000 rows.
I want to create a third text column with the data from text column 1 + text
column 2.
Is there an easy way to concatenate two text fields?
Thanks
Raju
maybe you can export the 2 columns into excel
eg. first column is in cell A1, second column is in cell B1
at C1 you type this formula =A1&B1, then copy this formula till the end of
the row, then you import it back to your table.
Susanna
"Raju" wrote:

> Hi all,
>
> I have a two text columns in my table with more than 100,000 rows.
> I want to create a third text column with the data from text column 1 + text
> column 2.
>
> Is there an easy way to concatenate two text fields?
>
> Thanks
> Raju
>
>
|||If you created a third column in your table you use an UPDATE statement
to do this like:
UPDATE Sometable
SET col3 = ISNULL(col1,'') + ISNULL(col2,'')
or in a view you could use the almost same syntax like:
SELECT ISNULL(col1,'') + ISNULL(col2,'') as col3
THE ISNULL(col1,'') syntax is related to the issue that in some cases
the attributes could be NULL rather than just an empty or regular
string and this would lead to a NULL result concatenating the two
values together.
HTH, Jens Suessmeyer.

how to concat/pivot rows to column?

hello,

I'm wondering how it's possible to have a select statement resultant rows concatenated into one row and column.
For example:
select letter from alphabet_table
a
b
c
d
e
...
26 rows returned.

Other than a cursor, how would I write a query to return the following:
row1: abcdefghijkl...

thanks in advance!There are a number of ways, none of which is truly generic (ie there isn't a "one size fits all" choice). Without understanding both what lead you to want to concatenate these values (and what rules you use to concatenate them), and what you will do with the concatenated result, I can't give you much useful advice.

-PatP|||Originally posted by Pat Phelan
There are a number of ways, none of which is truly generic (ie there isn't a "one size fits all" choice). Without understanding both what lead you to want to concatenate these values (and what rules you use to concatenate them), and what you will do with the concatenated result, I can't give you much useful advice.

-PatP

PatP, thanks for your reply. After posting I realize I should have included more information.
Here's more specifics:
CREATE TABLE [elements] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [varchar] (50) NOT NULL ,
[description] [varchar] (50) NULL ,
[code] [varchar] (5000) NOT NULL ,
[ord] [int] NOT NULL
) ON [PRIMARY]
GO

elements.code contains html tags, such as table, tr, td. I am using a stored procedure to build html code based on an input parameter. The parameter matches the 'name' column.
so to build a table, i would select the code and order by the ord column. the result is similar to the following:
<table width="100%" border="0">
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
(10 rows).
I would like to query the table based on the parameter passed to return the same results, except in one record:
<table width="100%" border="0"><tr><td></td><td></td><td></td></tr></table>
(1 row).

hope this helps clear it up|||That helps a bunch. The biggest problem that I see is that you can't allow your html table definition to exceed 4000 characters if you use 16 bit characters (aka UTF-8), or 8000 characters if you use 8 bit (OEM) characters. This could be a real problem for complex pages.

With that said, I'd start with:CREATE FUNCTION dbo.tableDef(@.name AS VARCHAR(50) RETURNS VARCHAR(8000) AS BEGIN
DECLARE
@.c VARCHAR(5000)
, @.r VARCHAR(8000)

SELECT @.r = ''
DECLARE z1 CURSOR FOR SELECT [code]
FROM [elements]
WHERE name = @.name
ORDER BY ord

OPEN z1
FETCH z1 INTO @.c

WHILE 0 = @.@.fetch_status
BEGIN
SET @.r = @.r + @.c
FETCH z1 INTO @.c
END

CLOSE z1
DEALLOCATE z1

RETURN @.r
END-PatP|||Oh yeah, usage would help, wouldn't it ? Sorry!SELECT [name], dbo.tableDef([name])
FROM [elements]
GROUP BY [name]-PatP|||Originally posted by Pat Phelan
Oh yeah, usage would help, wouldn't it ? Sorry!SELECT [name], dbo.tableDef([name])
FROM [elements]
GROUP BY [name]-PatP

many thanks, Pat. i was hoping there was a 'simpler' method of reaching this goal. sometimes i wish i could rewrite ms's implementation of the ansi select to include special tricks.
like: select + * from blah would concat results. ;)

i'll let you know how it works, i'm not too worried about the 4/8k character limit, i can always have a couple of columns.

thanks again.

How to compare vachar which type :20060324225008 with Datetime?

in my SQL 2000

the column importDate contain Date as a vachar , type is 20060324225008 ( 2006 -year , 03-month, 24-day)

I want to compare this column with today's date, how to transform it?

how to return value 20060324 not 20060324225008?

thank you

Grab the column as a string

string rawNumber = "20060324";

DateTime dtTime = Convert.ToDateTime(rawNumber);

Does it work?

|||

how can I get the value of column = 20060324, is was20060324225008 not 20060324

the problem is how to get 20060324 only

thank you

|||

Select LEFT(yourColumn,8) as newValue FROM yourTable

After this, you can use one of datetime functions to compare this date part with today's date part.

Wednesday, March 7, 2012

How to compare structure of two database ?

I have one database

and I create new database by copy everything from first db

I then alter some column on new database

and now I would like to compare two database

How can I do it ?

Stick out tongueStick out tongueStick out tongue

There is the manul way which I am sure you know of because like most of use we don't keep track of the changes that we make until time comes to roll the thing out.

There is a great good called RedGate SQL Compare (http://red-gate.com/products/SQL_Compare/index.htm) the tools are sort of expensive but well worth the money. Also if you are interested Microsoft is developing a product call Visual Studio for Database Developers that can be found on the MSDN site. Which esentially does the same thing and can be found on MSDN subscription download too.

|||I would write a script looking at syscolumns and sysobjects from both DB's and look where they do not match, this should get you changes to the DB.|||That is basically what Red Hat does, but it takes it a step furthor and generate the change script for you. I personally think that is worth 250.00|||

FYI, here is a simple script I'm using:

/*--Compare the differences in table schemas between 2 databases

--*/
/*--sample to call this stored procedure
exec p_comparestructure 'pubs','northwind'
--*/

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

create proc p_comparestructure
@.dbname1 varchar(250), --the name of the database to be comapred
@.dbname2 varchar(250) --the name of the database to be comapred
as
create table #tb1(TableName1 nvarchar(250),ColumnName nvarchar(250),Ordinal int,Iden bit,PrimaryKey bit,Type nvarchar(250),
Bytes int,Length int,BitsAfterDecimalPoint int,AllowNulls bit,DefaultValue nvarchar(500),ColumnDescription nvarchar(500))

create table #tb2(TableName2 nvarchar(250),ColumnName nvarchar(250),Ordinal int,Iden bit,PrimaryKey bit,Type nvarchar(250),
Bytes int,Length int,BitsAfterDecimalPoint int,AllowNulls bit,DefaultValue nvarchar(500),ColumnDescription nvarchar(500))

--Get the schema of database1
exec('insert into #tb1 SELECT
TableName=d.name,ColumnName=a.name,Ordinal=a.colid,
Iden=case when a.status=0x80 then 1 else 0 end,
PrimaryKey=case when exists(SELECT 1 FROM'+@.dbname1+'..sysobjects where xtype=''PK'' and name in (
SELECT name FROM'+@.dbname1+'..sysindexes WHERE indid in(
SELECT indid FROM'+@.dbname1+'..sysindexkeys WHERE id = a.id AND colid=a.colid
))) then 1 else 0 end,
Type=b.name,Bytes=a.length,Length=a.prec,BitsAfterDecimalPoint=a.scale, AllowNulls=a.isnullable,
DefaultValue=isnull(e.text,''''''),ColumnDescription=isnull(g.[value],'''''')
FROM'+@.dbname1+'..syscolumns a
left join'+@.dbname1+'..systypes b on a.xtype=b.xusertype
inner join'+@.dbname1+'..sysobjects d on a.id=d.id and d.xtype=''U'' and d.name<>''dtproperties''
left join'+@.dbname1+'..syscomments e on a.cdefault=e.id
left join'+@.dbname1+'..sysproperties g on a.id=g.id and a.colid=g.smallid
order by a.id,a.colorder')

--Get the schema of database2
exec('insert into #tb2 SELECT
TableName=d.name,ColumnName=a.name,Ordinal=a.colid,
Iden=case when a.status=0x80 then 1 else 0 end,
PrimaryKey=case when exists(SELECT 1 FROM'+@.dbname2+'..sysobjects where xtype=''PK'' and name in (
SELECT name FROM'+@.dbname2+'..sysindexes WHERE indid in(
SELECT indid FROM'+@.dbname2+'..sysindexkeys WHERE id = a.id AND colid=a.colid
))) then 1 else 0 end,
Type=b.name,Bytes=a.length,Length=a.prec,BitsAfterDecimalPoint=a.scale, AllowNulls=a.isnullable,
DefaultValue=isnull(e.text,''''''),ColumnDescription=isnull(g.[value],'''''')
FROM'+@.dbname2+'..syscolumns a
left join'+@.dbname2+'..systypes b on a.xtype=b.xusertype
inner join'+@.dbname2+'..sysobjects d on a.id=d.id and d.xtype=''U'' and d.name<>''dtproperties''
left join'+@.dbname2+'..syscomments e on a.cdefault=e.id
left join'+@.dbname2+'..sysproperties g on a.id=g.id and a.colid=g.smallid
order by a.id,a.colorder')
--and not exists(select 1 from #tb2 where TableName2=a.TableName1)
select Result=case when a.TableName1 is null and b.Ordinal=1 then 'Table:'+b.TableName2+' absent in'+@.dbname1
when b.TableName2 is null and a.Ordinal=1 then 'Table :'+a.TableName1+' absent in'+@.dbname2
when a.ColumnName is null and exists(select 1 from #tb1 where TableName1=b.TableName2) then @.dbname1+' ['+b.TableName2+'] doesn''t have column:'+b.ColumnName
when b.ColumnName is null and exists(select 1 from #tb2 where TableName2=a.TableName1) then @.dbname2+' ['+a.TableName1+'] doesn''t have column:'+a.ColumnName
when a.Iden<>b.Iden then 'Different identities'
when a.PrimaryKey<>b.PrimaryKey then 'Different Primary Key constraints'
when a.Type<>b.Type then 'Different column data types'
when a.Bytes<>b.Bytes then 'Bytes'
when a.Length<>b.Length then 'Different Lengths'
when a.BitsAfterDecimalPoint<>b.BitsAfterDecimalPoint then 'Different in BitsAfterDecimalPoint'
when a.AllowNulls<>b.AllowNulls then 'Different in AllowNulls options'
when a.DefaultValue<>b.DefaultValue then 'Different default values'
when a.ColumnDescription<>b.ColumnDescription then 'Different Column Descriptions'
else '' end,
*
from #tb1 a
full join #tb2 b on a.TableName1=b.TableName2 and a.ColumnName=b.ColumnName
where a.TableName1 is null or a.ColumnName is null or b.TableName2 is null or b.ColumnName is null
or a.Iden<>b.Iden or a.PrimaryKey<>b.PrimaryKey or a.Type<>b.Type
or a.Bytes<>b.Bytes or a.Length<>b.Length or a.BitsAfterDecimalPoint<>b.BitsAfterDecimalPoint
or a.AllowNulls<>b.AllowNulls or a.DefaultValue<>b.DefaultValue or a.ColumnDescription<>b.ColumnDescription
order by isnull(a.TableName1,b.TableName2),isnull(a.Ordinal,b.Ordinal)--isnull(a.ColumnName,b.ColumnName)
go

How to compare strings for equality in Transact SQL

I just learned that if a VARCHAR column contains 'ABC ' (three letters
and a space) then
SELECT * FROM ATABLE WHERE THECOLUMN = 'ABC'
will return the record since SQL Server incorrectly pads the shorter
value with spaces to the length of the longer before comparing them. Is
there a way to compare strings for equality that works correctly?
.Bill.trim?
SELECT * FROM ATABLE WHERE trim(THECOLUMN) = 'ABC'
"Bill" <no@.no.com> wrote in message
news:uhKlUmxMGHA.3728@.tk2msftngp13.phx.gbl...
>I just learned that if a VARCHAR column contains 'ABC ' (three letters
> and a space) then
> SELECT * FROM ATABLE WHERE THECOLUMN = 'ABC'
> will return the record since SQL Server incorrectly pads the shorter
> value with spaces to the length of the longer before comparing them. Is
> there a way to compare strings for equality that works correctly?
> --
> .Bill.|||THECOLUMN like 'ABC'
or
THECOLUMN+'$' = 'ABC'+'$'
"Bill" <no@.no.com> wrote in message
news:uhKlUmxMGHA.3728@.tk2msftngp13.phx.gbl...
>I just learned that if a VARCHAR column contains 'ABC ' (three letters
> and a space) then
> SELECT * FROM ATABLE WHERE THECOLUMN = 'ABC'
> will return the record since SQL Server incorrectly pads the shorter
> value with spaces to the length of the longer before comparing them. Is
> there a way to compare strings for equality that works correctly?
> --
> .Bill.|||In SQL Server use RTRIM
Jack Vamvas
________________________________________
__________________________
Receive free SQL tips - register at www.ciquery.com/sqlserver.htm
New article by Jack Vamvas - Improper Use of indexes on MS SQL: Server
2000 - www.ciquery.com/articles/useofindexes.asp
"Bill" <no@.no.com> wrote in message
news:uhKlUmxMGHA.3728@.tk2msftngp13.phx.gbl...
> I just learned that if a VARCHAR column contains 'ABC ' (three letters
> and a space) then
> SELECT * FROM ATABLE WHERE THECOLUMN = 'ABC'
> will return the record since SQL Server incorrectly pads the shorter
> value with spaces to the length of the longer before comparing them. Is
> there a way to compare strings for equality that works correctly?
> --
> .Bill.|||Grant wrote:

> trim?
> SELECT * FROM ATABLE WHERE trim(THECOLUMN) = 'ABC'
I must be missing something. Using trim gets the same incorrect result
as not using trim. The values 'ABC ' and 'ABC' are NOT equal. If I have
a table with a VARCHAR column that contains two rows with the values
'ABC ' and 'ABC', how do I write a SELECT statement that will return
the row that contains 'ABC' but not the row that contains 'ABC '?
.Bill.|||I think this is the problem he is having:
if 'ABC ' = 'ABC' print 'True' else print 'False'
Result: True
I am assuming he wants this condition to be False. In that base, he actually
doesn't want to trim the spaces.
"Jack Vamvas" <DELETE_BEFORE_REPLY_jack@.ciquery.com> wrote in message
news:dt2c11$m5j$1@.nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com...
> In SQL Server use RTRIM
> --
> Jack Vamvas
> ________________________________________
__________________________
> Receive free SQL tips - register at www.ciquery.com/sqlserver.htm
> New article by Jack Vamvas - Improper Use of indexes on MS SQL: Server
> 2000 - www.ciquery.com/articles/useofindexes.asp
> "Bill" <no@.no.com> wrote in message
> news:uhKlUmxMGHA.3728@.tk2msftngp13.phx.gbl...
>|||Grant and Jack, I think the OP wants to consider 'ABC' and 'ABC ' to be
*different* (in most configurations, SQL Server considers them equal because
the trailing spaces on varchar columns are ignored).
So, using RTRIM() does not help because it yields the same result the OP is
already getting.
"Jack Vamvas" <DELETE_BEFORE_REPLY_jack@.ciquery.com> wrote in message
news:dt2c11$m5j$1@.nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com...
> In SQL Server use RTRIM
> --
> Jack Vamvas
> ________________________________________
__________________________
> Receive free SQL tips - register at www.ciquery.com/sqlserver.htm
> New article by Jack Vamvas - Improper Use of indexes on MS SQL: Server
> 2000 - www.ciquery.com/articles/useofindexes.asp
> "Bill" <no@.no.com> wrote in message
> news:uhKlUmxMGHA.3728@.tk2msftngp13.phx.gbl...
>|||T-SQL has RTRIM() and LTRIM() but no TRIM().
For other info, please see my reply to Jack.
"Grant" <email@.nowhere.com> wrote in message
news:ejQpurxMGHA.3144@.TK2MSFTNGP11.phx.gbl...
> trim?
> SELECT * FROM ATABLE WHERE trim(THECOLUMN) = 'ABC'|||Aaron Bertrand [SQL Server MVP] wrote:

> Grant and Jack, I think the OP wants to consider 'ABC' and 'ABC ' to
> be different
That is exactly what I want.
.Bill.|||> will return the record since SQL Server incorrectly pads the shorter
> value with spaces to the length of the longer before comparing them.
Actually, SQL Server is ignoring the trailing spaces, but the result is the
same.
There are a few ways to solve this, JT's solution is pretty simple to
implement...

How to compare dynamic variable in proc

I have a table with 52 columns named 'Week1', 'Week2' etc. with values 1, 0 etc. I want to check values in each column. I have following lines in my procedure.

Declare @.l_str varchar(50),
@.l_count int

Select @.l_count = 1
Select @.l_str = 'Week' + Convert(varchar, @.l_count)
Now how do I compare the value stored in the @.l_str which should be wither 0 or 1 and not 'Week1'?

Is there any better method to compare read these 52 table variables?

Thanks in advanceCompare with what?|||Compare to check what does Week1 holds 1 or 0?|||I have a table with 52 columns named 'Week1', 'Week2' etc. with values 1, 0 etc.

It may be the liquid lunch, but

BBBBBBBBBWWWWWWWWWWWWWWWWWAAAAAAAAAAAAHHHAAHAHAHA

How to Compare 2007-9-11 and Month(GetDate()) ?

I am going to compare thie value 2007-9-11 (this value was retrived from the column(TxnDate) in my DataBase, type is DateTime)

I write code

select * from ZT_ModifyLog where Year(TXnDate) = Year(GetDate()) AND ( ( Month(TXnDate) < Month(GetDate()) ) and Month(TXnDate) >= Month(GetDate())-1)

it will like

select * from ZT_ModifyLog where Year(2007-9-11 ) = Year(GetDate()) AND ( ( Month(2007-9-11 ) < Month(GetDate()) ) and Month(2007-9-11 ) >= Month(GetDate())-1)

→ select * from ZT_ModifyLog where TxnDate(2007) = 2007 AND 10 < GetDate(10) and 9 >= 9 so return TXnDate between 2007/9/1~ 2007/9/30

but what if Month(GetDate())-13)?? when the -1 biger than 12... I guess the code will cause error ... but can't think out how to avoid and change my code

pleae help... thank you very much

Please do not open multiple threads for same question. Refer:http://forums.asp.net/t/1176161.aspx.

Friday, February 24, 2012

How to Combine two column in one table using SQL statement ?

Could you write the simple SQL statement from 'Combine two column in one table '?

I try to use 'Union' which combine two column in two table . thxYou can use the concatention operator (+):


SELECT
column1 + column2 AS myColumn
FROM
myTable

Terri|||If the columns are numeric then "+" will sum the column values.
If you do not desire this, you should use str() function

Check the below statement,

select ltrim(str(column1)) + ltrim(str(column2)) from mytable

How to collapsible a column when the report was designed in table mode?

Hi folks, I'm trying to collapse a column on a report that's designed in table mode. I was trying to mimick what happens in a matrix where you have a column that has a '+' in it that makes toggles the visibility of a column to its immediate right (The reason I'm not using Matrix mode is I continually get "out of memory" errors on the report I'm generating.).

When I select the column and mark visible to 'false' in the properties, it of course asks me for a TextBox. My problem is that I am unable to find a scenario where the textbox is "in the proper group". Is this something that's supported, and if so, I'd appreciate some pointers to lead me in the right direction.

Thanks.bump.. anyone have any clues?|||

I was able to get this to work fine in RS 2005. Where is the textbox that you are setting as the ToggleItem for the table column? I selected the textbox in the table header cell immediately to the left of the column that I wanted to toggle. What is the exact error you are seeing?

-Chris

|||Chris, thanks for your reply. My problem is I was selecting the whole column and trying to toggle the visibility on that. You can't do that; you've got to set the visibility on each portion individually (column header, group, detail). Thanks again.|||

Hi Aquineas..

I needed to do the same and managed to get it to work...

Create a text box outside of the table in the mainreport - with suitable text... Show / Hide Detail

and name the text box = ToggleColumns

Now highlight the column in the table and select the ToggleItem under Visibility and type ToggleColumns.

It works for me - even though the ToogleColumns isn't available in the list.

Cheers

Michael

|||I am having the same problem as Aquineas, I took Michael's suggestion but it doesn't seem to work for me. Having done what Micheal has suggested, I hides the column period and there is no way of getting it back on run time. I think I follow the instruction carefully. I am still looking for more suggestion.

How to collapsible a column when the report was designed in table mode?

Hi folks, I'm trying to collapse a column on a report that's designed in table mode. I was trying to mimick what happens in a matrix where you have a column that has a '+' in it that makes toggles the visibility of a column to its immediate right (The reason I'm not using Matrix mode is I continually get "out of memory" errors on the report I'm generating.).

When I select the column and mark visible to 'false' in the properties, it of course asks me for a TextBox. My problem is that I am unable to find a scenario where the textbox is "in the proper group". Is this something that's supported, and if so, I'd appreciate some pointers to lead me in the right direction.

Thanks.bump.. anyone have any clues?|||

I was able to get this to work fine in RS 2005. Where is the textbox that you are setting as the ToggleItem for the table column? I selected the textbox in the table header cell immediately to the left of the column that I wanted to toggle. What is the exact error you are seeing?

-Chris

|||Chris, thanks for your reply. My problem is I was selecting the whole column and trying to toggle the visibility on that. You can't do that; you've got to set the visibility on each portion individually (column header, group, detail). Thanks again.|||

Hi Aquineas..

I needed to do the same and managed to get it to work...

Create a text box outside of the table in the mainreport - with suitable text... Show / Hide Detail

and name the text box = ToggleColumns

Now highlight the column in the table and select the ToggleItem under Visibility and type ToggleColumns.

It works for me - even though the ToogleColumns isn't available in the list.

Cheers

Michael

|||I am having the same problem as Aquineas, I took Michael's suggestion but it doesn't seem to work for me. Having done what Micheal has suggested, I hides the column period and there is no way of getting it back on run time. I think I follow the instruction carefully. I am still looking for more suggestion.

Sunday, February 19, 2012

How to choose next value for identity column

Hi,

I have a table with its ID field set as an Identity column with "seed" and "increment" set to 1. Now, I have rows in there that I don't want to change. I'd like the next addtitions to the table to start at a specific value for their ID columns.

Basically, how can I specify a new starting value for an identity column?

Thanks,

Skip.I found this in SQL Server books online as well as the web. This sounds like what you might be looking for.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_dbcc_5lv8.asp

how to choose a Primary Key

Hi All,

I have a dilemn:
On one side, I have a column C1 which could be a primary key because it is never null, the value is unique and identify the record. The problem is its a char type and its lenght can be close to 30.
Then, I've planned to add another column C2 of int type as PK. But then I need to add a unique constraint index on C1. Does it improve performance anyway?

ThanksOnce you've got a primary key, adding a Unique constraint doesn't help performance. You should still add the constraint, it just won't help your performance.

-PatP|||I beg to differ, because unique constraint implicitly creates a unique index, thus - possibility of improving performance where the field(-s) is/are involved.|||when all around you are losing their heads.....

to answer your question generally
SQL Server 2000 Requires the primary key to be:
Unique
Not Null
16 columns or less for a composite key.

i cant help you with your di-lemon because the pk is such a personal thing. realistically your pk is your own and shouldnt be fondled by any other so i will go out on a limb here and say that what you have is fine.

However, {Opinion} i am a big fan of the monotonic key. simple, to the point, and oh, so very integer...mmmmn i can see my key right now in a dimly lit room with nothing on but an identity of 1,1 and sumptuous nonclustered index fill-factored just right.

i need a smoke..|||i need a smoke..My first guess would be that you need a bit more than a smoke, but you'll probably need to visit another web site for that!

I beg to differ, because unique constraint implicitly creates a unique index, thus - possibility of improving performance where the field(-s) is/are involved.On a slightly more serious note, I see a declared Primary Key (PK) as being somewhere between very important and critical for a table. Very little relational algebra is possible without a PK.

An Alternate Key (AK) or the equivalent unique constraint is a different matter. The AK should be declared in order to allow the database engine to do its job and ensure uniqueness of the AK. However, there is a cost assosciated with the AK, in that CPU and I/O time and disk space need to be used to enforce it. The benefits of a declared (and enforced) AK are important, but they aren't nearly as important in my opinion as the PK is. I've been willing to forego AK definitions if the potential benefits didn't outweigh the time/disk needed to acheive them.

While rdjabarov is right, and the AK might be useful, there are times that it can do more harm than good. From the pure relational standpoint of managing the table, I see the AK as optional. Of course, if you need to ensure uniqueness or if you have queries that will use the index, and the cost of maintaining it is less than the expected benefit, then I'm in favor of it. In fact, I'll even say that I'm generally in favor of AK definitions, but that you still need to use some judgement instead of just jumping in and declaring them everywhere they could be used.

-PatP|||While ... the AK might be useful, there are times that it can do more harm than good.bumph and nonsense

let's do an informal poll

of all the different threads we've seen in database forums (and some of us visit more than this one), what's the most common question?

that's right, "how do i remove my duplicates?"

i would say that, on balance, you will do good for 99 people by insisting on the unique constraint on the alternate key, and harm for 1 person, although i am hard pressed to think of the circumstances where this might occur

besides, if you (not you, pat, the reader) are really worried about the alleged "harm" of the unique constraint, then the solution is simple -- drop the stupid identity column and make the alternate key the real primary key

:) :) :)|||However, {Opinion} i am a big fan of the monotonic key. simple, to the point, and oh, so very integer

if you can revive some imperical statistics on the PK as Intelligent key vs PK as Monotonic key that would be excellent. but remember, this is a preference situation. sometimes the candidate is easily qualified to be a key and sometimes the addition of a surrogate is just as qualified.

so what is it that makes this an issue.
the inclusion of an additional column into the table that is taking up space in the dbf? or is it the suspected performance derived from SARGs based on monotonic integers?

basically this whole crappy argument comes down to who can write their name in the snow the quickest.

but for the sake of argument i will side with trotsky. :p|||I guess I've just run into too many cases that push the limits of available hardware.

One example of this is when gathering digital data from medical equipment. You often get data at rates that stress available hardware to the limit, and that data comes from well defined data sources. You often can't afford anything other than a PK on the collection table.

Some of the columns are 200+ bytes wide, and there are six of those columns that form the Alternate Key. This practically doubles the size of the row for each AK index you use. The PK being only four bytes is negligable in comparison, and is a lot more valuable to me.

While a bigger machine with a lot more disk would solve this particular problem, it would add a lot of cost and almost no benefit to the process.

There are lots of cases where data is coming in at high speed to a single centralized server. Basically a web farm being serviced by an app farm being serviced by a SQL Server. In this case, one SQL Server might be effectively servicing 50000 simultaneous users as well as a dozen or so analysts. Even though you could create a natural key, and in this case you might even choose to declare it as an alternate, the hardware won't support using that natural key as a foreign key.

Don't get me wrong... As I said in my previoius post I'm generally in favor of declaring AK even when I can't afford to use them as a PK, as long as it makes sense in the real world. Lots of things are really lovely in the gedankenexperiment that make a mess where the rubber actually meets the road!

-PatP|||Thank you all for your helpful replies :)

But I think I wasn't clear enough: what is better :
- to keep my column of type varchar(30) as PK
- to add another column of type int for example as PK and then add a unique constraint on my column of type varchar(30)

Once again, thank you for your support|||rcomaz

please provide a bit of background on your db
what kind of data is being stored there?
what is a basic business model summary?
what kind of data si being stored in the TIC(table in question)?
and how large is the TIC?
what are the related columns in other tables that reference the TIC?|||But I think I wasn't clear enough: what is better :
- to keep my column of type varchar(30) as PK
- to add another column of type int for example as PK and then add a unique constraint on my column of type varchar(30) Geez! Interrupting all of our lovely philosophical debates just to get the original question answered! ;)

On a more serious note, it doesn't matter all that much as long as your database is both small (say under 20 Gb) and low traffic (under 1000 SQL statements processed per minute), especially if you rarely use foreign keys. As your size/traffic/complexity grow, I expect that you'll want to go toward the simple INT column. A four byte INT key takes less space in indices, foreign keys, etc than a thirty byte character key, so it takes corresponding less time/disk/etc. to process.

-PatP|||hh;lkjhlkjolkhjlkjhn|||It's a no-brainer, just to second what Pat said, - it bottles down to how many values of a 4-byte size you can fit on a 8K page. This results in a number of logical reads when the optimizer scans through/seeks the index pages.|||It can be important how the PK is indexed if you had the PK as varchar then there had to be a reason as to why. If you will be storing character data in the PK then use varchar and do a clustered index for better searching.

Clustered Index = "When the DB searches data much like you would if you were trying to find a persons name in the phone book" Puts all the A's, B's, C's..... together for better performance.

Index = "Is like when you are looking up the actual number" SQL will put the rows in numeric order|||PK, even if not clustered, has to yield a unique row per value, which fits your definition for a nonclustered index, which in tern fits your clustered index definition...what books are you reading? Just a hint, - read from left to right, and once you reach the end of line, - do a carriage-return+line-fielf (vbCRLF, char(13)+char(10)) in your mind, so that you can continue reading the right way without confusing terms with definitions...But on a serious note, - come on, if you try to explain something to somebody, make sure you know it yourself, otherwise, - you're gonna run into a lot of trouble here ;)|||...be nice to the noobies...|||I really appreciate all your comments, thanks :D

By the way, from the business point of view, the varchar(30) field is the unique identifiant of the item (which is a media matrix - like an iso image), thus it could be a good candidate for PK... I'm just afraid of the response time of queries, and this even with a clustered index.|||How many records are you talking about? How big is this database going to get? Is response time your biggest concern?|||I must appologize I stand corrected clustered indexes store data in sequential order. It was 3am when i wrote the reply. I meant to explain clustered and non clustered indexes. I also like to explain things in "normal terms" not "geek". I could have went into leaf pages, why there is a unique index, creation of a unique key column (although you should always create one you dont have to) SQL Server can handle duplicate rows by adding unique idenifiers in the background, how SQL stores data, but like i said it was 3am. I am a geek so dont get all flustered by my comment. God knows Rdjabaroy might come back at me with vb or vba code, "but on a serious note":

OleDbConnection con = new OleDbConnection(strConnect);
con.Open();
string strInsert = "INSERT INTO tblRdjabaroy VALUES('Is great at VB!!!')";

OleDbCommand cmdInsert = new OleDbCommand(strInsert, con);

do while (Rdjabaroy != 'cool')
{
cmdInsert.ExecuteNonQuery();
}

con.Close();

// =)

No seriously I know what you mean. People, including myself, come here for answers. I dont want the wrong answers either. So I do apologize|||First, it's RDJABAROV, not RDJABAROY...but I was called worse things ;) (consult with blindman, he used to be good at it LOL)

if object_id('dbo.tblRdjabaroy') is not null
exec sp_rename 'dbo.tblRdjabaroy', 'dbo.tblRDjabarov', 'object'
else
create table dbo.tblRDjabarov ([jayblaze2's_definition_of_rdjabarov] varchar(8000) not null )
go
create trigger dbo.trig_blaze_jay_twice
on dbo.tblRDjabarov
for insert
as
exec master.dbo.xp_cmdshell 'net send jayblaze2 "...Hmmmm...another one ;)"'
rollback tran
go