Friday, March 9, 2012

Declare an array of int in SQL Server

Hi All,
I want declare an array of int in SQL Server
please help me to convert the following code from VB to TSQL
----
Dim md_mon(12) As Integer
md_mon(1) = 31
----
ThanksThere are no arrays in SQLServer. Maybe if you explain your requirements
someone can suggest another alternative.

--
David Portas
SQL Server MVP
--|||Majid Mohammadian (Mohammadian59@.yahoo.com) writes:
> I want declare an array of int in SQL Server
> please help me to convert the following code from VB to TSQL
> ----
> Dim md_mon(12) As Integer
> md_mon(1) = 31
> ----

SQL and Visual Basic are languages that work from very different mindsets,
and for a successful rewrite from VB to SQL it is often best to start from
the beginning. In VB you would typically to things in loops, to iterate
over items in a set of data, but in SQL you should always strive to use
commands that operate on the entire set at the same time. That is when
you actually win performance.

SQL does not have arrays, but there are tables, and tables are a lot broader
concept than array. So in this case:

CREATE TABLE md_mon (monthno int NOT NULL PRIMARY KEY,
noofdays tinyint NOT NULL)

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

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||If the purpose of your array was to store the number of days in each month
then as an alternative in TSQL you could calculate the number of days for a
given month like this:

DECLARE @.dt DATETIME
SET @.dt = '20040101' -- January 2004

SELECT DAY(DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(DAY,1-DAY(@.dt),@.dt))))

--
David Portas
SQL Server MVP
--|||Erland Sommarskog <sommar@.algonet.se> wrote in message
> SQL does not have arrays, but there are tables, and tables are a lot broader
> concept than array. So in this case:
> CREATE TABLE md_mon (monthno int NOT NULL PRIMARY KEY,
> noofdays tinyint NOT NULL)

FYI: You can also create a table variable, like:

DECLARE @.tblMonth TABLE (
MonthNo int,
NumDays int
)

... and then use it like any real table:

INSERT INTO @.tblMonth...
SELECT * FROM @.tblMonth...

No comments:

Post a Comment