0

Can we define a variable of type array in SQL Server?

I have a table and this pk type is datetime.

CREATE TABLE [dbo].[tblTest]
(
 [TestDate] [datetime] NOT NULL, -- this column is the primary key
 [UserId] [int] NOT NULL,
 [RotationType] [int] NOT NULL
)

And I need a query to update userId

UPDATE TABLE dbo.tblTest
SET RotationType = 1
WHERE TestDate IN (@testDates)

How can I declare this @testDates variable?

marc_s
759k185 gold badges1.4k silver badges1.5k bronze badges
asked Mar 31, 2021 at 15:55
3

1 Answer 1

2

you can use table variables:

declare @tblvar as table (TestDate datetime)
insert into @tblvar values (('2021-09-01'),...);
UPDATE TABLE dbo.tblTest
SET RotationType = 1
WHERE TestDate IN (select TestDate from @tblvar)

or you can declare it as type so you can pass it to procs:

declaration phase :

create type DateTimeArray as table (TestDate datetime);
CREATE PROCEDURE funcname (@inputDates DateTimeArray)
as
UPDATE TABLE dbo.tblTest
SET RotationType = 1
WHERE TestDate IN (select TestDate from @inputDates)
end 

calling:

declare @tblvar as DateTimeArray;
insert into @tblvar values (('2021-09-01'),...);
exec funcname @tblvar
answered Mar 31, 2021 at 16:06
Sign up to request clarification or add additional context in comments.

2 Comments

i will use this variables in sp, so i need pass this parameter how can i it ?
see my updated asnwer , didn't test , so it might have some minor syntax issue , but you got the idea ;)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.