Skip to content

Tag: sql-server

Dates returned as columns in SQL Select

My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic. This returns that dates as rows. What I am looking for is a way to make these dates return as the columns

Filter an XML column in SQL Server

I have an xml type column productsXML in product table I want to find all the rows that have <products></products>. I tried this: This is returning all the rows that have products tag and understandably so. Is there a way to filter only those rows that have <products></products>? Answe…

SSMS SQL Identify purchases who only buy one specific item

I want to find customers who have only bought fruit in their purchase. My data looks like this: I want this: Thinking I need a where clause, grouped by ID and Purchase_date? Answer You can try to use Having with condition aggregate function to write the logic. Buy fruit (COUNT with fruit count will be greater…

Dynamic SQL – Use declared VARCHAR in SET SQL string

How to use the declared variable @CodeID inside the SQL string? When I run following statement I get the “Invalid object name (..)” error. Answer It looks to me that you need two levels of dynamic SQL, with the first level inserting the database name (from #folders), and the second level inserting…

SQL Query group by for a beginner

I’m quite new to SQL Server and was wondering if it was possible to run a query like this. I have a table with the following fields: USER, WORKSTATION, DURATION (seconds) Each USER can use multiple workstations and each workstation can be used by multiple USERs. In the table I have records like: I would…

Find Multiple Substring from a String Using SQL

I have a column log. I need to extract values from that log column and make 4 new columns My table: Output I need: Answer If the string really always follows exactly that format, you can use something funky like this: Which gives: This abuses the PARSENAME function, which is meant to parse 4 part named object…

SQL Query to merge several views into one

I was trying to create a new view out of 3 or 4 other views/tables. TableA: title_id homeTeam 1234 WSV 5678 SSV 7890 NULL 4321 SCC TableB: title_id awayTeam 1234 SSV 5678 SFV 7890 NULL 4321 KFC TableC: title_id homeTeam 1234 SSV 5678 NULL 7890 AAB 4711 BFG I would like to generate a new view out of those thre…