Showing posts with label write. Show all posts
Showing posts with label write. Show all posts

Thursday, March 29, 2012

Cursor Query?

Does anyone have any links on how to iterate over a set of rows in Sql 2005, I have never did this before...If someone would be so kind to write a basic cursor query just so i can atleast see how its implemented? Any links on how to create one?

In general, I try to avoid cursors; as a generalization I would suggest that set-based operations are usually faster than record-based operations. If you need to use a cursor, look up cursors in books online. What specifically are you trying to do?

You might want to give a look to this article about a TABLE OF NUMBERS; at times, this is useful:

http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html

Another thing is that many things can be "iterated through" just simply by joining one table to another.

|||If you are really going to use a cursor, look at books online under "FETCH". It has a full set of examples.|||Well i have a column called sort_order and the sort_order should be 12345678910 etc.... but the sort order got jacked up not its like 112233445668899 so I wanted to write a cursor to go through every row and where there is an duplicate replace it with the appropiate count.....Do you have a better way to do this?|||My knee-jerk reaction to this partial description is that a cursor is not best. How are you planning on computing the new sort_id if you have a duplicate sort id?|||

Well what happen is that my sort_order column got thrown off due to some other issues....the computing of the sorting is correct when new items that need to sorted are created....its just we have some exsisting items that sort_order is thrown off due to other issues...Thats why i wanted to create a cursor to get all the exsisting sort orders and correct them by executing a sql script that use a cursor to iterate over all the ones who sort order is screwed to and correct them....does that make more sense? what would you suggest....I have an update query right now that will reset a particular set of items sort orders back to normal and everything is great but i think that take too long to do for all the sets of items that i have that need to be sorted.....what do think?

Now when i run this against a set of items that sort is off this will set the sort back to 12345678910111213 etc..... but i have alot of items to do this with, and that was the reason for the idea of creating the cursor.....would i be able to do this another way?

Declare @.intcounter int

set @.intcounter = 0

UPDATE tableName

SET @.intcounter = sort_order = @.intcounter + 1

FROM TableName AS st LEFT OUTER JOIN

TableName1 ON st.id = TableName.ID

WHERE (st.is_active = 1) AND (TableName1.ID = 13132)

|||

I am puzzling over the LEFT OUTER JOIN with the WHERE ... AND (TableName1.ID = 13132). Doesn't the AND condition force this into basically being an INNER JOIN?

Also, since the only contribution from TableName1 is to filter based on ID, do you even need to join to this table? Can't you just filter based on ST.ID = 13132?

If you don't have to join to the OUTER (or maybe INNER) table, this should be a rather efficient update -- provided you have an index on the ID column.

Please check me on this.

|||This was part of a bigger Sql statement that i had executed...As you can see I am not a sql GURU...lol but It works for what i need it to do...I just need it to work for every indiviudal ID...I dont want to have to enter in all the different ID's to fix the sort order...thats why i thought to use the cursor to fix this issue.....cause from what i see i can get it to iterate over all the rows and update the sort order for the ID in a table....|||

Consider doing it like this:

Declare @.intcounter int
set @.intcounter = 0

UPDATE tableName
SET @.intcounter = @.intcounter + 1,
sort_order = @.intcounter
WHERE is_active = 1
AND ID = 13132

This should iterate through the records you want fine and provide a sequence of number 1-N for N records that meet the WHERE / AND criteria. It will be efficient PROVIDED that you have an index on the ID column.

|||

I guess I sort-of need to make a confession here, too: I tend to loathe cursors -- I guess it is kind of a personal prejudice, but in this case I definitely have a bias and it is probably better if you are aware of that bias. I'd rather not go into that bias, but it is better for you if you know that this particular bias is present.


Kent

|||

I have one more question........I have a table with two columns..... the id column is not a primary key

column1ID column2_Numbers

1 2

1 2

1 3

1 4

1 5

1 6

1 7

In this table you see id 1 has some numbers that are duplicated......I want to know if this table was filled with a set of ids that have these numbers associated with them how would i go about counting all the IDS that had duplicate numbers associated with them? like since ID 1 has dups then my count should increase to 1 and so on?

|||

One way to count the number of column1IDs that have duplicates is something like:

select count(*)
from ( select column1ID,
count(*) as idCount
from yourTable
group by columnID
having count(*) > 1
) x

|||

what does the "x" do and why would i use the Having clause instead of doing it like

Select Count(id) From tableName

Where number_column = number_column?

|||

The "x" is arbitrary; you must give an arbitrary name to a derived table (the expression in the parends); I just happened to choose "x"; it could be any name. I am considering the "number_column" issue; that looks like something i do not yet understand.

Yes, that is definitely a misunderstanding by me. My last SELECT code is wrong; sorry, I will see about fixing that.

|||

I think it needs to look more like:

select count(*)
from ( select column1ID,
column2_numbers,
count(*) as idCount
from yourTable
group by columnID, column2_numbers
having count(*) > 1
) Y

The code:

Select Count(id) From tableName
Where number_column = number_column?

will not work as you wish; this code will select all rows of the table where NUMBER_COLUMN is not null

I suppose if you are wanting to find the NUMBER_COLUMN for a given ID you can do:

select column2_numbers,
count(*) as idCount
from yourTable
where column1ID = 1
group by column2_numbers
having count(*) > 1

Tuesday, March 27, 2012

Cursor or Several Stored Procs

Would I be better served (ie faster execution & general database sexiness)
using the dreaded, hated, and loathsome cursor or to attempt to write a
series of stored procedures (6-12) to work with result sets of matching
criteria?
I am importing a large number of csv's to update existing information &
execute stored proc's aimed at updating / calculating an individual's data
based with multiple conditions.Hi
It depends on what you are doing! Usually it is better (and quicker) to use
a set based solution. If your code has a significant amount of branching
calling separate procedures may be an advantage.
HTH
John
"Clamps" wrote:

> Would I be better served (ie faster execution & general database sexiness)
> using the dreaded, hated, and loathsome cursor or to attempt to write a
> series of stored procedures (6-12) to work with result sets of matching
> criteria?
> I am importing a large number of csv's to update existing information &
> execute stored proc's aimed at updating / calculating an individual's data
> based with multiple conditions.
>
>sql

Sunday, March 25, 2012

Cursor help please

Hello. I'm am trying to write a cursor in SQL Server 2000 that looks in a table with a list of tablenames (UpdateTables), looks up the number of rows in that table and then enters the number of rows in the second column of the lookup table against the correct tablename. I have written the following but am getting an error message saying that I need to declare the variable @.tblName

GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[sp_UpdateTablesUpdate]
as
DECLARECrExtractUpdateCount CURSOR FOR SELECT Tablename FROM dbo.UpdateTables
DECLARE @.tblName char(50)

OPEN CrExtractUpdateCount
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName

WHILE @.@.FETCH_STATUS = 0
BEGIN
UPDATE UpdateTables
SET Number_Rows = (select count (*) from @.tblName)
WHERE dbo.[UpdateTables].[Tablename] = @.tblName
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName
END
CLOSE CrExtractUpdateCount
DEALLOCATE CrExtractUpdateCount

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

any help much appreciated.Hi,

Variable should be handled as follows.
go throu. the following lines for example..

DECLARE @.tblName char(50)
set @.tblName='Employee' --Table name
DECLARE @.count char(500)
set @.count='(select count (*) from ' + rtrim(isnull(@.tblName,0)) + ')'
PRINT @.count

Then Use the variable, @.count to update the second column.
Hope U understand.

Regards,
Sharmila|||Thanks for help but am now getting bad syntax errors around
set @.count='(select count (*) from ' + rtrim(isnull(@.tblName,0)) + ')'|||The two SQL statements I have tried now are:

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

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[sp_UpdateTablesUpdate]
as
DECLARECrExtractUpdateCount CURSOR FOR SELECT Tablename FROM dbo.UpdateTables
DECLARE @.tblName char(50)
DECLARE @.NoRows char(50)

OPEN CrExtractUpdateCount
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName

WHILE @.@.FETCH_STATUS = 0
BEGIN
UPDATE UpdateTables
SET Number_Rows = 'select count (*) from @.tblName'
WHERE dbo.[UpdateTables].[Tablename] = @.tblName
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName
END
CLOSE CrExtractUpdateCount
DEALLOCATE CrExtractUpdateCount

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

The above piece of code simply puts the text select count (*) from @.tblName in each row in destination table.
There fore I tried:

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

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[sp_UpdateTablesUpdate]
as
DECLARECrExtractUpdateCount CURSOR FOR SELECT Tablename FROM dbo.UpdateTables
DECLARE @.tblName char(50)
DECLARE @.NoRows char(50)

OPEN CrExtractUpdateCount
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName

WHILE @.@.FETCH_STATUS = 0
BEGIN
UPDATE UpdateTables
SET Number_Rows = (select count (*) from @.tblName)
WHERE dbo.[UpdateTables].[Tablename] = @.tblName
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName
END
CLOSE CrExtractUpdateCount
DEALLOCATE CrExtractUpdateCount

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

Which is giving error
Server: Msg 137, Level 15, State 2, Procedure sp_UpdateTablesUpdate, Line 14
Must declare the variable '@.tblName'.

I don't understand this as the variable is working perfectly in the next line.

I also tried putting the select statement into a variable called @.NoRows which didn't work either (same two results as above)

Anymore help much appreciated.|||Thanks for the help.
Managed to crack it by putting @.NoRows into a temp table temprows then updating UpdateTables from this. As follows

if exists (select * from dbo.sysobjects where id =

object_id(N'[dbo].[cp_UpdateTablesUpdate]') and OBJECTPROPERTY(id,

N'IsProcedure') = 1)
drop procedure [dbo].[cp_UpdateTablesUpdate]
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE [dbo].[cp_UpdateTablesUpdate]
as
DECLARECrExtractUpdateCount CURSOR FOR SELECT Tablename FROM

dbo.UpdateTables
DECLARE @.tblName char(50)
DECLARE @.NoRows char(50)
DECLARE @.NoRowsC char(50)

OPEN CrExtractUpdateCount
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName

WHILE @.@.FETCH_STATUS = 0
BEGIN
set @.NoRows = 'select count (*) from ' + @.tblName
insert into temprows exec (@.NoRows)
UPDATE UpdateTables
SET Number_Rows = temprows.execreturn
from temprows
WHERE dbo.[UpdateTables].[Tablename] = @.tblName
FETCH NEXT FROM CrExtractUpdateCount
INTO @.tblName
END
CLOSE CrExtractUpdateCount
DEALLOCATE CrExtractUpdateCount

GO

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

exec cp_UpdateTablesUpdate

Thursday, March 22, 2012

Current user in SQL

Hi

Is there a variable or a possibility to use the current user in sql?

I would like to create an update trigger and write the user that made the change in the affected table!

Thanks!

Try SUSER_NAME() for the login or USER_NAME() for the database user.

|||

Pick your poison ;-)

SELECT SUSER_SNAME(),USER_NAME(),CURRENT_USER


Denis The SQL Menace
http://sqlservercode.blogspot.com
http://sqlblog.com/blogs/denis_gobo/default.aspx

Tuesday, March 20, 2012

Current executing task

Hi everyone

I'm trying to write a monitoring application for SSIS packages deployed on my machine. I know I can look at running packages via the DtsRuntime.Application object's GetRunningPackages method. Does anyone know if there is any way one can view tasks in that package that are currently being executed?

Cheers

Sachin

Wow! Brilliant! I was hoping for at least one reply... I guess I have to question whether this is possible or not. :)|||

You can, but it comes down to implementing the IDTSEvents interface, and/or overriding the packageEvents class.

You will then override the the function's OnPreExecute/OnPostExecute in your execution + monitoring application.

This "get current running tasks" would be much eaiser if there were not in bug in Application.GetRunningPackages() in which in InstanceId (the unique job execution identifier) does not match the execution id in the logs. If it did, you could call get running Packages, and then use logging to determine what was running and be close to on the money.

To me, the bug is analogous to logging the SQL Server spid in SQL profiler, but having it never match "select spid from master..sysprocesses".

|||

sachin.rao wrote:

Wow! Brilliant! I was hoping for at least one reply... I guess I have to question whether this is possible or not. :)

You posted at 17:09 and then sent this reply at 09:20 on the next working day. GIve people a chance! Also, nobody is required to answer you know.

As jaegd said, you can derive this by looking at the OnPreExecute/OnPostExecute events.

-Jamie

|||

Ok. Thanks jaegd.

Jamie - I realize that nobody has to answer. No offense intended. It was just that 50-odd people had viewed the topic and there hadn't been a response, so I was just thinking out aloud. That's all.

Sunday, March 11, 2012

Currency

hi,
i would like to write a sql function which takes 3 parameters.
1. Source currency type
2. destination currency type
3. Amount to be converted
I need the dynamic rates.
Does anybody hav any idea about how to go with this.
Thanks in advance,
Vinu
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200605/1Are you using SQL Server 2005 ? Therefore you could use Webservices to
call an currency service synchronously or async. by storing the data
in a currency table. That sure is possible with SQL 2000 but it MORE
easier with SQL 2005.
HTH, Jens Suessmeyer.
--
http://www.sqlserver2005.de
--

Currency

hi,
i would like to write a sql function which takes 3 parameters.
1. Source currency type
2. destination currency type
3. Amount to be converted
I need the dynamic rates.
Does anybody hav any idea about how to go with this.
Thanks in advance,
Vinu
Message posted via droptable.com
http://www.droptable.com/Uwe/Forum...server/200605/1Are you using SQL Server 2005 ? Therefore you could use Webservices to
call an currency service synchronously or async. by storing the data
in a currency table. That sure is possible with SQL 2000 but it MORE
easier with SQL 2005.
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--

curious result

How can I write a query to return non distinct results?Your question is a bit vague but maybe this example will help.
Duplicate last names in the Aithors table:

SELECT au_lname, COUNT(*)
FROM Pubs.dbo.Authors
GROUP BY au_lname
HAVING COUNT(*)>1

If you need more help please read the following article about the best
way to post your problem.

http://www.aspfaq.com/etiquette.asp?id=5006

--
David Portas
SQL Server MVP
--|||this works except I'm needing distinct combinations of several fields
such as

SELECT x, y, z, COUNT(*)
FROM table
GROUP BY x
HAVING COUNT(*)>1

David Portas wrote:

>Your question is a bit vague but maybe this example will help.
>Duplicate last names in the Aithors table:
>SELECT au_lname, COUNT(*)
> FROM Pubs.dbo.Authors
> GROUP BY au_lname
> HAVING COUNT(*)>1
>If you need more help please read the following article about the best
>way to post your problem.
>http://www.aspfaq.com/etiquette.asp?id=5006
>|||William Kossack (kossackw@.njc.org) writes:
> this works except I'm needing distinct combinations of several fields
> such as
> SELECT x, y, z, COUNT(*)
> FROM table
> GROUP BY x
> HAVING COUNT(*)>1

And that query is good for you? Or are you asking for more assistance?
In the latter case, please post:

o CREATE TABLE statment for the your table
o INSERT statement with sample data.
o The desired result given the sample.

if we have to guess what you are looking for, odds are that our
guesses will be wrong.

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Friday, February 17, 2012

CSV Render Engine

Hi

I have Reporting Services hosted on a server which has Workgroup edition of SQL Server which does not support csv export. I would like to write a csv Renderer.

I am not sure how complex this task is likely to be.
Are there any White Papers or samples that would assist ?
Any advice to point me in the right direction would be most appreciated.

Regards

JohnJames

Hi Chaps

I have just found an article on MSDN stating that
writing a Render is a very complex operation.
Will now seek another alternative.


Regards

JohnJames

Tuesday, February 14, 2012

csv and leading zeroes

I'm trying to write the contents of a csv file to a table, but I am having problems with fields with leading zeroes. Whenever I save as csv I lose the leading zeroes. Does anybody know how to prevent this?

I don't know what data type you are using but you can use Decimal and Numeric so you can set precision and scale. Try the link below for details. Hope this helps.

http://msdn2.microsoft.com/en-us/library/ms187746.aspx