Code Snippet about T-SQL Query

2014/05/311 min read
bookmark this
Responsive image

Table of Contents

Introduction

This post provides a sample T-SQL code snippet that demonstrates using CASE expressions, string concatenation for address formatting, and subqueries.

T-SQL Query Example

select pl.Id as 'ID',
MyType =
case
		when exists (select * from [TestDB].[dbo].SomeTable fsl (nolock) where fsl.Id = pl.Id) then
		'Type1'
		else
		'Type2'
End
,
av.AttachmentId as 'Another ID',
Convert(varchar, av.DateLastUpdated, 101) as 'Date',
Convert(varchar, av.DateEntered, 101) as 'Date 2',
Address =
(select TOP 1
RTRIM(adr.Address1) + '' + COALESCE(adr.Address2,'') + ',' + adr.CityName + ',' + COALESCE(adr.CountyRegionName,'') + ',' + adr.StateProvCode + RTRIM(adr.PostalZipCode)as 'Address'
from [TestDB].[dbo].[TestDBAddress] as pladd (nolock)

inner join [TestDB].[dbo].[Address] as adr (nolock)

on pladd.AddressID = adr.AddressID
where pladd.Id = pl.Id)
from [TestDB].[dbo].[TestDB] as av (nolock)

inner join [TestDB].[dbo].[TestDB1] as pla (nolock)

on av.Id = pla.Id
where
and av.DateLastUpdated between '2014-05-01' AND '2014-05-31'

Conclusion

This T-SQL snippet demonstrates common patterns including CASE expressions for conditional values, scalar subqueries for address concatenation, and date range filtering. Adapt the table and column names to fit your own database schema.