Monday 26 November 2018

MSSQL - Assign result of dynamic sql to a variable


Watch this example on YouTube



1. Table


CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [SomeNumber] [int] NULL,
    [test] [bit] NOT NULL,
    [isFinalSale] [bit] NOT NULL,
    [isThisFinalSale] [bit] NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [ProductID] ASC,
    [test] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]

GO


2. Query

Declare @SelectedIds varchar(max) = '1,2,10'
Declare @Sql nvarchar(max) = 'Select @res = Count(*) from Product Where ProductID in  (' + @SelectedIDs + ')'
Declare @Result int
Exec sp_executesql @Sql, N'@res int out', @Result out
Select @Result

No comments:

Post a Comment