Showing posts with label tsql. Show all posts
Showing posts with label tsql. Show all posts

Friday, February 24, 2012

arrays in tsql?

Hi;

I have been writing a lot of short tsql scripts to fix a lot of tiny
database issues.

I was wondering if a could make an array of strings in tsql that I
could process in a loop, something like

array arrayListOfTablesToProcess = { "orders", "phone",
"complaints"}

for( int i = 0; i < arrayListOfTablesToProcess.length; i++ )
delete from arrayListOfTablesToProcess[i]

Can you do something like this in tsql?

I should probably stop asking all of these questions.

Is there a good book on TSQL alone ( I'm not interested in wizards,
just scripting )...that is short?

SteveThere are no arrays in TSQL. You are thinking in terms of a procedural
solution rather than a set-based solution. In general, you should be able to
use a table and set-based, SELECT/UPDATE/DELETE statements to process
"lists" of data. If you define your problem more specifically someone here
may be able to help with the set-based solution.

--
David Portas
----
Please reply only to the newsgroup
--|||Hi

In addition to David's post check out:

http://www.algonet.se/~sommar/arrays-in-sql.html

John

"Steve" <stevesusenet@.yahoo.com> wrote in message
news:6f8cb8c9.0310040337.52427942@.posting.google.c om...
> Hi;
> I have been writing a lot of short tsql scripts to fix a lot of tiny
> database issues.
> I was wondering if a could make an array of strings in tsql that I
> could process in a loop, something like
>
> array arrayListOfTablesToProcess = { "orders", "phone",
> "complaints"}
> for( int i = 0; i < arrayListOfTablesToProcess.length; i++ )
> delete from arrayListOfTablesToProcess[i]
>
>
> Can you do something like this in tsql?
> I should probably stop asking all of these questions.
> Is there a good book on TSQL alone ( I'm not interested in wizards,
> just scripting )...that is short?
> Steve

Array in TSQL?

Hello,
I have some code that adds a new user. The new user has a checkboxlist of
items which they can be associated with. I would like to send this list of
items to TSQL along with the new user information. I would guess to combine
the selected items like so: "6,4,8,19,2".
Kind of do the following:
INSERT into tblUser (fields) VALUES (data)
Declare @.userID as integer
SET @.UserID = @.@.IDENTITY
for each item in @.Selected
INSERT into tblSelections (field) VALUE (item, @.UserID)
I know above isn't exactly possible, but can something similiar be done? I
dont want to have to run a proc for each item from my asp.net pages...
Thanks,
David Lozzi
Web Applications Developer
dlozzi@.(remove-this)delphi-ts.comIt would definetely be easiest to call a proc each time. Othewise you
could pass in the comma seperated string into the proc, and then do a
while loop with that string.
While CharIndex(",",@.Selected) != 0
Begin
-- Get Value before first comma code
-- Insert value code
-- Delete first value and comma code
End|||David Lozzi (DavidLozzi@.nospam.nospam) writes:
> I have some code that adds a new user. The new user has a checkboxlist
> of items which they can be associated with. I would like to send this
> list of items to TSQL along with the new user information. I would guess
> to combine the selected items like so: "6,4,8,19,2". >
> Kind of do the following:
> INSERT into tblUser (fields) VALUES (data)
> Declare @.userID as integer
> SET @.UserID = @.@.IDENTITY
> for each item in @.Selected
> INSERT into tblSelections (field) VALUE (item, @.UserID)
> I know above isn't exactly possible, but can something similiar be done? I
> dont want to have to run a proc for each item from my asp.net pages...
See http://www.sommarskog.se/arrays-in-sql.html#iterative for some
solutions.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||You have missed the foundations of RDBMS and really need to get a book
or a class before you try to code anything.
You want to violate First Normal Form (1NF). All data values are
scalar; there are no arrays. Each of those attribures would be a
separate column.
Rows are not records; fields are not columns; tables are not files.
We do not put silly redundant prefixes like "tbl-" on table names.
Look up ISO-11179.
I hope you know that IDENTITY cannot be a relational key by definition.
But you are using a bad thing in the wrong way. It mimics a
sequential file record number counter without your intervention when
you declare it as part of the DDL.
Do you know about check digits, a Regular Expression or some other rule
to validate your user id?
SQL is a set-oriented language, so you can insert a query result into a
base table or updatable VIEW. You are writing SQL like it was a 3GL.
You need a lot more help thanyou can get in a Newsgroup.|||I believe SQL Server 2005 supports arrays. I'm just getting into it, though.
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
A watched clock never boils.
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1130887553.702237.72860@.g49g2000cwa.googlegroups.com...
> You have missed the foundations of RDBMS and really need to get a book
> or a class before you try to code anything.
> You want to violate First Normal Form (1NF). All data values are
> scalar; there are no arrays. Each of those attribures would be a
> separate column.
> Rows are not records; fields are not columns; tables are not files.
> We do not put silly redundant prefixes like "tbl-" on table names.
> Look up ISO-11179.
> I hope you know that IDENTITY cannot be a relational key by definition.
> But you are using a bad thing in the wrong way. It mimics a
> sequential file record number counter without your intervention when
> you declare it as part of the DDL.
> Do you know about check digits, a Regular Expression or some other rule
> to validate your user id?
> SQL is a set-oriented language, so you can insert a query result into a
> base table or updatable VIEW. You are writing SQL like it was a 3GL.
>
> You need a lot more help thanyou can get in a Newsgroup.
>|||trival, wrtite a user function that converts a comma seperated list into a
table (the sql equiv of an array)
create function dbo.parseList (@.s varchar(2000))
returns @.values table (value varchar(2000))
as begin
declare @.v varchar(2000) ,@.i int
set @.i = patIndex('%,%',@.s)
while @.i > 0 begin
insert @.values values (substring(@.s,1,@.i-1))
set @.s = substring(@.s,@.i+1,len(@.s) - @.i)
set @.i = patIndex('%,%',@.s)
end
insert @.values values (@.s)
return
end
then call like:
INSERT into tblUser (fields) VALUES (data)
SET @.UserID = scope_identity()
INSERT tblSelections (field,userid)
select value, @.UserID
from dbo.parseList(@.selected)
-- bruce (sqlwork.com)
"David Lozzi" <DavidLozzi@.nospam.nospam> wrote in message
news:e03WQ9y3FHA.3600@.TK2MSFTNGP12.phx.gbl...
> Hello,
> I have some code that adds a new user. The new user has a checkboxlist of
> items which they can be associated with. I would like to send this list of
> items to TSQL along with the new user information. I would guess to
> combine the selected items like so: "6,4,8,19,2".
> Kind of do the following:
> INSERT into tblUser (fields) VALUES (data)
> Declare @.userID as integer
> SET @.UserID = @.@.IDENTITY
> for each item in @.Selected
> INSERT into tblSelections (field) VALUE (item, @.UserID)
> I know above isn't exactly possible, but can something similiar be done? I
> dont want to have to run a proc for each item from my asp.net pages...
> Thanks,
> --
> David Lozzi
> Web Applications Developer
> dlozzi@.(remove-this)delphi-ts.com
>
>|||Thanks for your help.
:-|
David Lozzi
Web Applications Developer
dlozzi@.(remove-this)delphi-ts.com
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1130887553.702237.72860@.g49g2000cwa.googlegroups.com...
> You have missed the foundations of RDBMS and really need to get a book
> or a class before you try to code anything.
> You want to violate First Normal Form (1NF). All data values are
> scalar; there are no arrays. Each of those attribures would be a
> separate column.
> Rows are not records; fields are not columns; tables are not files.
> We do not put silly redundant prefixes like "tbl-" on table names.
> Look up ISO-11179.
> I hope you know that IDENTITY cannot be a relational key by definition.
> But you are using a bad thing in the wrong way. It mimics a
> sequential file record number counter without your intervention when
> you declare it as part of the DDL.
> Do you know about check digits, a Regular Expression or some other rule
> to validate your user id?
> SQL is a set-oriented language, so you can insert a query result into a
> base table or updatable VIEW. You are writing SQL like it was a 3GL.
>
> You need a lot more help thanyou can get in a Newsgroup.
>|||>I believe SQL Server 2005 supports arrays
Really?
Roji. P. Thomas
Net Asset Management
http://toponewithties.blogspot.com
"Kevin Spencer" <kevin@.DIESPAMMERSDIEtakempis.com> wrote in message
news:%23NDUr8z3FHA.3296@.TK2MSFTNGP09.phx.gbl...
>I believe SQL Server 2005 supports arrays. I'm just getting into it,
>though.
> --
> HTH,
> Kevin Spencer
> Microsoft MVP
> .Net Developer
> A watched clock never boils.
> "--CELKO--" <jcelko212@.earthlink.net> wrote in message
> news:1130887553.702237.72860@.g49g2000cwa.googlegroups.com...
>|||Kevin Spencer (kevin@.DIESPAMMERSDIEtakempis.com) writes:
> I believe SQL Server 2005 supports arrays. I'm just getting into it,
> though.
No, not more than SQL 2000. That is, you can transform a list to table
with a function or similar.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||There are actually two methods to approach this situation. They are:
1. Making use of sp_xml_preparedocument and sp_xml_removedocument and
2. Custom split function (If you want the code snippet for custom split
function .. write back)
Sample table structure:
--
Create table StudentMaster
(
StudentID int IDENTITY(1,1) NOT NULL,
StudentName varchar(100),
StudentAge int
)
Create table StudentDetails
(
StudentID int,
SubjectName varchar(10)
)
Method 1:
--
Create proc InsertStudent
@.StudentName varchar(100),
@.StudentAge int,
@.SubjectString varchar(1000)
AS
Begin Tran StudentTransaction
/* Local Variable Declarations */
Declare @.NewRowId int
Declare @.SubjectXmlDoc int
/* Insert Master record and get identity value */
Insert Into StudentMaster (StudentName, StudentAge) Values (@.StudentName,
@.StudentAge)
-- Retreive the last identity value inserted into the Identity column
(StudentID)
Select @.NewRowId = SCOPE_IDENTITY()
/* Replace dummy identity value with actual id value */
Select @.SubjectString = Replace(@.SubjectString, '123456',
Convert(varchar(10), @.NewRowId))
/* XML Bulk Insert the Subjects */
-- The below line creates XML document and returns numeric ID
Exec sp_xml_preparedocument @.SubjectXmlDoc OUTPUT, @.SubjectString
Insert into StudentDetails (StudentId, SubjectName)SELECT StudentId,
SubjectName FROM OPENXML (@.SubjectXmlDoc, '/root/row') WITH (StudentId int,
SubjectName varchar(100))
-- Deletes the XML document
Exec sp_xml_removedocument @.SubjectXmlDoc
Commit Tran StudentTransaction
/* To test SP */
Exec InsertStudent 'test', 12, '<root><row StudentId="123456"
SubjectName="Maths"/><row StudentId="123456" SubjectName="Science"/></root>'
"David Lozzi" wrote:

> Hello,
> I have some code that adds a new user. The new user has a checkboxlist of
> items which they can be associated with. I would like to send this list of
> items to TSQL along with the new user information. I would guess to combin
e
> the selected items like so: "6,4,8,19,2".
> Kind of do the following:
> INSERT into tblUser (fields) VALUES (data)
> Declare @.userID as integer
> SET @.UserID = @.@.IDENTITY
> for each item in @.Selected
> INSERT into tblSelections (field) VALUE (item, @.UserID)
> I know above isn't exactly possible, but can something similiar be done? I
> dont want to have to run a proc for each item from my asp.net pages...
> Thanks,
> --
> David Lozzi
> Web Applications Developer
> dlozzi@.(remove-this)delphi-ts.com
>
>
>

Array in TSQL

Hi all,

I have data like this :

POHDR;JAKARTA;St.1
DTL;1. ;00248337;8996006855701 ;083;041;002; 7,812.50; 312,500.00; 284,091.00; 8,875.00

first row is the PO header and the second is the detail. This data was collected using Export Import Wizard from flatfile and put it in one column. I want to split the header and the detail into different table and map each column separated by ; to a proper field. For this work I should check every column separated by ; with CHARINDEX function but I have to write the TSQL as much as the count of ;. It would be better if we can use array to simplify the code.

Can we use array in Transact SQL ? since I have no clue referring to SQLBOL. Thanks in advance.

Best regards,

Hery

Hi Hery,

You can add identity column to the table so you can asume that the ids with odd numbers (i.e. 1, 3, 5 ..) as PO Header and the Ids with Even Numbers as Details..

Regarding Arrays.. I am sorry there is no such concept.. but you can go through following link to get it work..

http://www.sommarskog.se/arrays-in-sql.html

Hope this will help you..

|||Hi SajidAttar,

Thanks for the article, it helps me much.

Best regards,

Hery|||

Hi..

Glad to help.. and to be honest.. effort goes to the author..Smile

All the best.

Array in TSQL

Hi all,

I have data like this :

POHDR;JAKARTA;St.1
DTL;1. ;00248337;8996006855701 ;083;041;002; 7,812.50; 312,500.00; 284,091.00; 8,875.00

first row is the PO header and the second is the detail. This data was collected using Export Import Wizard from flatfile and put it in one column. I want to split the header and the detail into different table and map each column separated by ; to a proper field. For this work I should check every column separated by ; with CHARINDEX function but I have to write the TSQL as much as the count of ;. It would be better if we can use array to simplify the code.

Can we use array in Transact SQL ? since I have no clue referring to SQLBOL. Thanks in advance.

Best regards,

Hery

Hi Hery,

You can add identity column to the table so you can asume that the ids with odd numbers (i.e. 1, 3, 5 ..) as PO Header and the Ids with Even Numbers as Details..

Regarding Arrays.. I am sorry there is no such concept.. but you can go through following link to get it work..

http://www.sommarskog.se/arrays-in-sql.html

Hope this will help you..

|||Hi SajidAttar,

Thanks for the article, it helps me much.

Best regards,

Hery|||

Hi..

Glad to help.. and to be honest.. effort goes to the author..Smile

All the best.

Sunday, February 19, 2012

Array in TSQL

Hi all,

I have data like this :

POHDR;JAKARTA;St.1
DTL;1. ;00248337;8996006855701 ;083;041;002; 7,812.50; 312,500.00; 284,091.00; 8,875.00

first row is the PO header and the second is the detail. This data was collected using Export Import Wizard from flatfile and put it in one column. I want to split the header and the detail into different table and map each column separated by ; to a proper field. For this work I should check every column separated by ; with CHARINDEX function but I have to write the TSQL as much as the count of ;. It would be better if we can use array to simplify the code.

Can we use array in Transact SQL ? since I have no clue referring to SQLBOL. Thanks in advance.

Best regards,

Hery

Hi Hery,

You can add identity column to the table so you can asume that the ids with odd numbers (i.e. 1, 3, 5 ..) as PO Header and the Ids with Even Numbers as Details..

Regarding Arrays.. I am sorry there is no such concept.. but you can go through following link to get it work..

http://www.sommarskog.se/arrays-in-sql.html

Hope this will help you..

|||Hi SajidAttar,

Thanks for the article, it helps me much.

Best regards,

Hery|||

Hi..

Glad to help.. and to be honest.. effort goes to the author..Smile

All the best.

Sunday, February 12, 2012

Are there such a thing as arrays in TSQL?

I'm have a stored procedure that iterates through a list of numbers and adds an item for each number (user id) some of these ids are duplicates which is fine even necessary for the first part of my query but for the last I need to ensure that no duplicates id's are passed to the stored procedure, in this case called 'spInsertForBackupNote'. My thoughts here was to do something like this:

SET @.Note_Buffer = @.UserID -- @.Note_Buffer being some kind of array?

IF @.Note_Buffer = @.UserID -- If its been added to the buffer we dont execute sp
BEGIN
Do Nothing here
END

ELSE

BEGIN
EXECUTE spInsertForBackupNote @.FK_UserID, @.FK_NoteID
END

I know this would never work because it would always be false since I just added the same userid to the buffer that I want to add. But I think you see my problem. I know it should be an easy one but my TSQL is limited. I've posted the whole sp. Hope someone can help.

CREATE PROCEDURE spInsertAssignedNotesByList
@.FK_UserIDList NVARCHAR(4000) = NULL,
@.FK_NoteIDList NVARCHAR(4000) = NULL,
@.By_Who INT,
@.UserID INT

AS
SET NOCOUNT ON

DECLARE @.Length INT
DECLARE @.Note_Length INT
DECLARE @.Note_Buffer INT

DECLARE @.FirstUserIDWord NVARCHAR(4000)
DECLARE @.FirstNoteIDWord NVARCHAR(4000)

DECLARE @.FK_UserID INT
DECLARE @.FK_NoteID INT

SELECT @.Length = DATALENGTH(@.FK_UserIDList )
SELECT @.Note_Length = DATALENGTH(@.FK_NoteIDList )

DECLARE @.TempFK_NoteIDList NVARCHAR(4000) --= NULL
DECLARE @.Temp_NoteLength INT

SET @.TempFK_NoteIDList = @.FK_NoteIDList
SET @.Temp_NoteLength = DATALENGTH(@.FK_NoteIDList )

-- IF @.Length > @.Note_Length -- If we have more users than notes

BEGIN

WHILE @.Length > 0
BEGIN

IF @.Length > 0

EXECUTE @.Length = PopFirstWord @.FK_UserIDList OUTPUT, @.FirstUserIDWord OUTPUT
SELECT @.FK_UserID = CONVERT(INT, @.FirstUserIDWord)

IF @.Length > 0
BEGIN

SET @.FK_NoteIDList = @.TempFK_NoteIDList
SET @.Note_Length = @.Temp_NoteLength

WHILE @.Note_Length > 0
BEGIN
EXECUTE @.Note_Length = PopFirstWord @.FK_NoteIDList OUTPUT, @.FirstNoteIDWord OUTPUT
SELECT @.FK_NoteID = CONVERT(INT, @.FirstNoteIDWord)

IF @.Note_Length > 0
EXECUTE spInsertAssignedNoteDetail @.FK_UserID, @.FK_NoteID

SET @.Note_Buffer = @.UserID
EXECUTE spInsertForBackupNote @.FK_UserID, @.FK_NoteID, @.By_Who, @.UserID -- NEW HERE
END
END

END
END

----------------
GOThere are not arrays in TSQL (at least the current version).

You can simulate it by placing the values into a temp table (perhaps by passing in a delimited string, and then using a user defined function that returns a table variable). Then, once you have the table, you can do what TSQL is best at, Set operations.|||can you show an example of how to display the contents of a table variable?

Thanks|||What do you mean by "display"? SQL Server runs on the server, and as such really does not expose a user interface.|||the UDF returns a table variable and I need to bind to it and display the contents on a .net web page.|||At the end of the SP,

SELECT * FROM TableVariable

Do an ExecuteReader or similar and bind the datareader to the grid, whatever.|||I am using a strongly typed dataset and am using com.executenonquery to bind to a datagrid and the results are:
I get back the columns names from the function or sp (they both do the same) but the columns are empty.