Showing posts with label declare. Show all posts
Showing posts with label declare. Show all posts

Wednesday, March 7, 2012

Compare 2 char strings?

Hi,

How do i compare 2 dates which are char datatypes?

Example:

declare @.d1 char(24)

declare @.d2 char(24)

SET @.d1 ='2007-04-24 00 :00:00:000'

SET @.d2 = '2007-04-24 00 :00:00:000'

IF(@.d1=@.d2)

print '1'

Else

print '2'

output:

out put is 2 instead of 1.

It works fine if i use >= or <= but not =.

--Kodela.

You should be using "==". "=" is an assignment operator, not an equality operator.|||

Phil Brammer wrote:

You should be using "==". "=" is an assignment operator, not an equality operator.

In T-SQL?|||

Adamus Turner wrote:

Phil Brammer wrote:

You should be using "==". "=" is an assignment operator, not an equality operator.

In T-SQL?

True that. Heck, I just jumped in when he said "==" worked. His code worked fine for me in T-SQL as written.|||

When I paste this code into my query analyzer, I get '1'. What you have there should work. Are you always comparing dates?

Mike Binkley.

|||

Hi Phil,

It didn't work for me.I got this error when i used '=='

Incorrect syntax near '='.

--Kodela.|||

Because you're dealing with timestamps that use seconds, no 2 dates will ever be equal.

01/01/2001 01:01:000 will never be equal to 01/01/2001 01:02:000

You must format the date so there is no timestamp hh:mmTongue Tieds to compare.

SELECT CONVERT(CHAR(10),GETDATE(),110), CONVERT(CHAR(10),GETDATE(),110)

--Notice the difference:

SELECT CONVERT(CHAR(10),GETDATE(),110), GETDATE()

These above dates are equal. So you must do the following:

declare @.d1 char(10)

declare @.d2 char(10)

SET @.d1 ='2007-04-24 00 :00:01:000'

SET @.d2 = '2007-04-24 00 :03:21:000' --This is still equal to the above date

IF(@.d1=@.d2)

print '1'

Else

print '2'

Setting char(10) instead of char(24) will accomplish the same task

Adamus

|||

kodela wrote:

Hi Phil,

It didn't work for me.I got this error when i used '=='

Incorrect syntax near '='.

--Kodela.

Yeah, I'm blind. I admit it among my other flaws in this post. Should've kept my fingers away from the keyboard... |||

It worked for you because the seconds are the same. The poster didn't realize he posted correct syntax on accident. If you change the seconds the code will not work.

declare @.d1 char(24)

declare @.d2 char(24)

SET @.d1 ='2007-04-24 00 :00:00:001'

SET @.d2 = '2007-04-24 00 :00:00:000'

IF(@.d1=@.d2)

print '1'

Else

print '2'

Notice the "001" on the seconds. You have to use char(10)

Adamus

|||

Adamus,

I cannot change char to 10 because i need to compare both date and time.

My query takes a parameter value in datetime and checks whether that datettime exists in table or not and print the output accordingly.

kodela.

|||

kodela wrote:

Adamus,

I cannot change char to 10 because i need to compare both date and time.

My query takes a parameter value in datetime and checks whether that datettime exists in table or not and print the output accordingly.

kodela.

Then you cannot use an = comparison unless you first compare the date and then the time. You are forced to use <= or >= or BETWEEN

But be careful with BETWEEN when using timestamps because it will exclude remainders of days.

Adamus

|||

kodela wrote:

Adamus,

I cannot change char to 10 because i need to compare both date and time.

My query takes a parameter value in datetime and checks whether that datettime exists in table or not and print the output accordingly.

kodela.

Then the above will work just fine. Just know that if it's one second off, the comparison will not be equal.|||

kodela wrote:

Adamus,

I cannot change char to 10 because i need to compare both date and time.

My query takes a parameter value in datetime and checks whether that datettime exists in table or not and print the output accordingly.

kodela.

Convert to Char(10) to know the days are the same --> then compare Char(24)

Adamus

|||

Do you want to compare DATES or do you want to compare DATE STRINGS?

Code Snippet

declare @.dt1 datetime

declare @.dt2 datetime

declare @.str1 char(24)

declare @.str2 char(24)

--Set the STRING values (notice "A" in april comes before 'N' in 'November)

SET @.str1 ='November 1, 2007'

SET @.str2 = 'April 1, 2008'

--IMPLICIT conversion of STRING values to DateTime values

set @.dt1 = @.str1

set @.dt2 = @.str2

if @.str1 > @.str2

select 'String 1 Is Bigger'

if @.str2 > @.str1

select 'String 2 is Bigger.'

if @.dt1 > @.dt2

select 'Date 1 is Bigger'

if @.dt2 > @.dt1

select 'Date 2 is Bigger'

|||

I'm not sure how this would work at all. What if you're comparing dates in the same month? ...and the month are not in alpabetical order.

Adamus

Tuesday, February 14, 2012

Command USE with variable

Why I can′t use the command USE with variable?

declare @.banco varchar(20)
select @.banco='xpto'
USE @.banco

I have try in other way without success

DECLARE @.banco varchar(50)
declare @.SQL varchar(50)
select @.banco='xpto'
print @.banco
select @.SQL='USE '+@.banco
print @.SQL
exec(@.SQL)

Help me, please.

Rodrigo

It is executed at both compile time and run time, so I presume that is the reason. Not all commands can use variables in place of constants. the TOP command, for instance, only takes constants until it was altered in SQL 2005. For USE sysntax and description:

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

|||

I am developing a routine to desfragment
the indexes of all tables of the server... I′ve found one in the books online (DBCC SHOWCONTIG session), but I ′m trying to convert it to defrag all objetcs in all databases of my instance. So I have think in a "Cursor" that get the name of the databases in the "sysdatabases" system table. Than set each database to current and run the script. Fallow the script:

For this, I have think in set the database to run the script on the database context.

Can you help me?

/*Perform a 'USE <database name>' to select the database in which to run the script.*/ -- Declare variables SET NOCOUNT ON DECLARE @.tablename VARCHAR (128) DECLARE @.execstr VARCHAR (255) DECLARE @.objectid INT DECLARE @.indexid INT DECLARE @.frag DECIMAL DECLARE @.maxfrag DECIMAL -- Decide on the maximum fragmentation to allow SELECT @.maxfrag = 30.0 -- Declare cursor DECLARE tables CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' -- Create the table CREATE TABLE #fraglist ( ObjectName CHAR (255), ObjectId INT, IndexName CHAR (255), IndexId INT, Lvl INT, CountPages INT, CountRows INT, MinRecSize INT, MaxRecSize INT, AvgRecSize INT, ForRecCount INT, Extents INT, ExtentSwitches INT, AvgFreeBytes INT, AvgPageDensity INT, ScanDensity DECIMAL, BestCount INT, ActualCount INT, LogicalFrag DECIMAL, ExtentFrag DECIMAL) -- Open the cursor OPEN tables -- Loop through all the tables in the database FETCH NEXT FROM tables INTO @.tablename WHILE @.@.FETCH_STATUS = 0 BEGIN -- Do the showcontig of all indexes of the table INSERT INTO #fraglist EXEC ('DBCC SHOWCONTIG (''' + @.tablename + ''') WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS') FETCH NEXT FROM tables INTO @.tablename END -- Close and deallocate the cursor CLOSE tables DEALLOCATE tables -- Declare cursor for list of indexes to be defragged DECLARE indexes CURSOR FOR SELECT ObjectName, ObjectId, IndexId, LogicalFrag FROM #fraglist WHERE LogicalFrag >= @.maxfrag AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0 -- Open the cursor OPEN indexes -- loop through the indexes FETCH NEXT FROM indexes INTO @.tablename, @.objectid, @.indexid, @.frag WHILE @.@.FETCH_STATUS = 0 BEGIN PRINT 'Executing DBCC INDEXDEFRAG (0, ' + RTRIM(@.tablename) + ', ' + RTRIM(@.indexid) + ') - fragmentation currently ' + RTRIM(CONVERT(varchar(15),@.frag)) + '%' SELECT @.execstr = 'DBCC INDEXDEFRAG (0, ' + RTRIM(@.objectid) + ', ' + RTRIM(@.indexid) + ')' EXEC (@.execstr) FETCH NEXT FROM indexes INTO @.tablename, @.objectid, @.indexid, @.frag END -- Close and deallocate the cursor CLOSE indexes DEALLOCATE indexes -- Delete the temporary table DROP TABLE #fraglist GO |||

Here is one way with using sp_MSforeachdb and DBCC DBREINDEXALL

Both of these things are undocumented and you might not want to run it on a production server

EXEC sp_MSForEachDB 'IF ''?'' NOT IN (''master'', ''model'', ''msdb'', ''tempdb'')
DBCC DBREINDEXALL (''?'') '

-- nobody can be connected to the db for the above statement to work

also you could do something like this

DECLARE @.SQL NVarchar(4000)
SET @.SQL = ''
SELECT @.SQL = @.SQL + 'EXEC ' + NAME + '..sp_MSforeachtable @.command1=''DBCC DBREINDEX (''''*'''')'', @.replacechar=''*''' + Char(13)
FROM MASTER..Sysdatabases
where dbid > 6
PRINT @.SQL

EXEC (@.SQL)

However if you exceed 4000 characters this will fail

Denis the SQL Menace

http://sqlservercode.blogspot.com/

|||

For EXECUTE you can use varchar(8000), or in 2005 you can use varchar(max).

|||Please don't use undocumented system stored procedures. They are not guaranteed to remain in every version of SQL Server. In fact we removed several system stored procedures or modified their behavior in SQL Server 2005.|||

Set options or use statement executed within dynamic SQL is only valid within that scope. So in your case, you have to perform the USE and the DBCC statement within the same dynamic SQL execution like:

exec('use ' + @.somedb + '; dbcc index...')

Sunday, February 12, 2012

Comma seperated IDS in SELECT query with IN.

How can I use list of comma separated IDS in SELECT query with IN.
DECLARE @.TaskID varchar(200)
SET @.TaskID = '(30,32)'
SELECT DISTINCT UserID
FROM tbl_UserTask
WHERE TaskID IN @.TaskIDI do not want to use Dynamic SQL|||Look at Dejan's example
IF OBJECT_ID('dbo.TsqlSplit') IS NOT NULL
DROP FUNCTION dbo.TsqlSplit
GO
CREATE FUNCTION dbo.TsqlSplit
(@.List As varchar(8000))
RETURNS @.Items table (Item varchar(8000) Not Null)
AS
BEGIN
DECLARE @.Item As varchar(8000), @.Pos As int
WHILE DATALENGTH(@.List)>0
BEGIN
SET @.Pos=CHARINDEX(',',@.List)
IF @.Pos=0 SET @.Pos=DATALENGTH(@.List)+1
SET @.Item = LTRIM(RTRIM(LEFT(@.List,@.Pos-1)))
IF @.Item<>'' INSERT INTO @.Items SELECT @.Item
SET @.List=SUBSTRING(@.List,@.Pos+DATALENGTH(',
'),8000)
END
RETURN
END
GO
/* Usage example */
SELECT t1.*
FROM TsqlSplit('10428,10429') AS t1
declare @.inList varchar(50)
set @.inList='10428,10429'
select od.* from [order details] od
INNER JOIN
(SELECT Item
FROM dbo.TsqlSplit(@.InList)) As t
ON od.orderid = t.Item
"Adarsh" <shahadarsh@.gmail.com> wrote in message
news:1140690585.836794.90030@.g14g2000cwa.googlegroups.com...
>I do not want to use Dynamic SQL
>|||Look at this function by Dejan Sarka:
http://solidqualitylearning.com/blo.../10/22/200.aspx
ML
http://milambda.blogspot.com/|||Thanks Uri,
It solved my problem.|||http://www.aspfaq.com/2248
"Adarsh" <shahadarsh@.gmail.com> wrote in message
news:1140690353.281661.41550@.v46g2000cwv.googlegroups.com...
> How can I use list of comma separated IDS in SELECT query with IN.
> DECLARE @.TaskID varchar(200)
> SET @.TaskID = '(30,32)'
> SELECT DISTINCT UserID
> FROM tbl_UserTask
> WHERE TaskID IN @.TaskID
>|||or
DECLARE @.TaskID varchar(200)
SET @.TaskID = '30,32'
SELECT DISTINCT UserID
FROM tbl_UserTask
WHERE ','+@.TaskID+',' like '%,'+cast(TaskID as varchar)+',%'
Madhivanan