I have this Sql puzzle i'm using Sql server 2005
the following query works fine
DECLARE #query VARCHAR(200)
DECLARE #colname varchar(50)
CREATE TABLE #temp (ID INT IDENTITY PRIMARY KEY , value VARCHAR(50))
INSERT INTO #temp VALUES ('first')
SET #colname = 'myCol'
SET #query = 'SELECT value AS' + #colname + ' FROM #temp'
EXEC(#query)
DROP TABLE #temp
BUT
if i do this
SET #colname = (SELECT value FROM tablename WHERE id = 12) --valid selection
or
SELECT #colname = value FROM tablename WHERE id = 12 --valid selection
I don't get any result , i get a message saying :
(1 row(s) affected)
AND ERROR Message:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '1'.
Any body knows what is going on with this thing Thanks
As per the comments you need to guard against the value being NULL because nothing was assigned or the column name being an invalid SQL Server identifier.
You can do the former by checking ##ROWCOUNT after the assignment and the second by using QUOTENAME
DECLARE #query VARCHAR(200)
DECLARE #colname VARCHAR(50)
CREATE TABLE #temp
(
ID INT IDENTITY PRIMARY KEY,
value VARCHAR(50)
)
INSERT INTO #temp
VALUES ('first')
SELECT #colname = QUOTENAME(value)
FROM tablename
WHERE id = 12
IF ##ROWCOUNT <> 1
BEGIN
RAISERROR('Unexpected rowcount',16,1)
RETURN
END
SET #query = 'SELECT value AS ' + #colname + ' FROM #temp'
EXEC(#query)
DROP TABLE #temp
Your #temp table has identity column and your query only insert to the #temp table once..
So you only have ID = 1.
ID = 12 is not exists.
This query will be give the result.
DECLARE #query VARCHAR(200)
DECLARE #colname varchar(50)
CREATE TABLE #temp (ID INT IDENTITY PRIMARY KEY , value VARCHAR(50))
INSERT INTO #temp VALUES ('first')
SELECT #colname = value FROM #temp WHERE id = 1
SET #query = 'SELECT value AS' + #colname + ' FROM #temp'
EXEC(#query)
DROP TABLE #temp
Related
Due to storing values from language specific diacritics (Spanish, French, German) I am trying to change the datatype of a column to Unicode datatype.
Varchar to nvarchar
char to nchar
So all column datatype to its respective Unicode datatype.
For all tables in a specific database.
Can it be possible to do in a single statement? Because doing with alter statement is time consuming.
ALTER TABLE dbo.Employee
ALTER COLUMN FirstName NVARCHAR(255) NOT NULL
Many thanks.
First we create a temporary table and define the variables we need for the changes.
Then we fill the table by fetching the columns that need to change.
I entered the fetch command below and everything is clear.
Then, for each row in the table, we make the desired changes in the database.
Also, a column in a table may have a value of NULL, so you must replace the NULL values with a value before changing the column.
I replaced the NULL values with a value of 0.
The code below works perfectly and correctly.
Only I entered dbo for schema name in search of columns. See what your database schema name is
--Container to Insert Id which are to be iterated
Declare #temp1 Table
(
tablename varchar(100),
columnname varchar(100),
columnlength varchar(100),
columntype varchar(100)
)
--Container to Insert records in the inner select for final output
Insert into #temp1
SELECT t.TABLE_NAME,c.COLUMN_NAME,c.CHARACTER_MAXIMUM_LENGTH,c.DATA_TYPE FROM information_schema.tables t
join INFORMATION_SCHEMA.COLUMNS c on t.TABLE_NAME = c.TABLE_NAME
WHERE t.table_schema='dbo'
and (DATA_TYPE = 'varchar' OR DATA_TYPE = 'char')
-- Keep track of #temp1 record processing
Declare #tablename varchar(100)
Declare #columnname varchar(100)
Declare #columnlength varchar(100)
Declare #columntype varchar(100)
Declare #SQL VarChar(1000)
Declare #vary varchar(100)
Declare #final varchar(1000)
While((Select Count(*) From #temp1)>0)
Begin
Set #tablename=(Select Top 1 tablename From #temp1)
Set #columnname=(Select Top 1 columnname From #temp1)
Set #columnlength=(Select Top 1 columnlength From #temp1)
Set #columntype=(Select Top 1 columntype From #temp1)
if(#columntype = 'varchar')
Set #columntype='nvarchar'
else
Set #columntype='nchar'
--set null value with 0 value
SELECT #SQL = 'UPDATE ' + #tablename + ' SET ' + #columnname + ' = 0 WHERE ' + #columnname + ' IS NULL'
Exec ( #SQL)
SELECT #SQL = 'ALTER TABLE '
SELECT #SQL = #SQL + #tablename
select #vary = ' ALTER COLUMN ' + #columnname + ' ' + #columntype + '(' + #columnlength + ') NOT NULL'
select #final = #sql + #vary
--select #final
Exec ( #final)
Delete #temp1 Where tablename=#tablename and columnname = #columnname
End
I'm writing a query against a table A where I want to find out if a row in table A has fields that are null. The thing is that these fields are dynamic and are found in another table B.
Normally you would write,
Table A ....
WHERE A.myField1 IS NOT NULL AND A.myField2 IS NOT NULL
But in this case I want to do
table A ....
WHERE (some columns in table **A** specified in table **B**) IS NOT NULL
Is it possible to do this?
If I understand your question correctly, you may try to generate dynamic SQL statement and execute this statement:
-- Tables
CREATE TABLE #TableA (
MyField1 int,
MyField2 int,
MyField3 int,
MyField4 int,
MyField5 int,
MyField6 int
)
CREATE TABLE #TableB (
FieldName nvarchar(50)
)
INSERT INTO #TableB
(FieldName)
VALUES
('MyField1'),
('MyField2'),
('MyField3')
-- Declarations
DECLARE
#stm nvarchar(max),
#err int
-- Statement generation
SET #stm = N''
SELECT #stm = #stm +
N'AND (' +
[FieldName] +
N' IS NOT NULL) '
FROM #TableB
SET #stm =
N'SELECT * FROM #TableA WHERE ' +
STUFF(#stm, 1, 4, N'')
-- Execution
PRINT #stm
EXEC #err = sp_executesql #stm
IF #err = 0
PRINT 'OK'
ELSE
PRINT 'Error'
Generated statement:
SELECT *
FROM #TableA
WHERE (MyField1 IS NOT NULL) AND (MyField2 IS NOT NULL) AND (MyField3 IS NOT NULL)
I need to reorder columns in the final SELECT statement in a stored procedure. Column orders needs to be fetched from another table.
I have a solution based on dynamic SQL. Is there any better way to do it? I have around 100 columns to return with millions of rows for an Excel export. Is there any other performance optimized solution other than a dynamic query?
Please find sample code below for my current solution.
IF OBJECT_ID( 'tempdb..#TempColumns') IS NOT NULL
BEGIN
DROP TABLE #TempColumns
END
IF OBJECT_ID( 'tempdb..#TempColumnsOrder') IS NOT NULL
BEGIN
DROP TABLE #TempColumnsOrder
END
CREATE TABLE #TempColumns
(
ID INT IDENTITY,
FirstName VARCHAR(MAX),
LastName VARCHAR(MAX),
Gender VARCHAR(MAX)
)
INSERT INTO #TempColumns
VALUES ('ABC', 'DEF', 'MALE'), ('PR', 'ZA', 'FEMALE'), ('ERT', 'GFG', 'MALE')
CREATE TABLE #TempColumnsOrder
(
ID INT IDENTITY,
ColumnName VARCHAR(MAX),
ColumnOrder INT
)
INSERT INTO #TempColumnsOrder
VALUES ('FirstName', 3), ('LastName', 2), ('Gender', 1)
SELECT * FROM #TempColumns
SELECT * FROM #TempColumnsOrder
DECLARE #script VARCHAR(MAX)
SELECT #script = 'SELECT '
SELECT #script = #script + ColumnName + ','
FROM #TempColumnsOrder
ORDER BY ColumnOrder
PRINT #script
SELECT #script = SUBSTRING(RTRIM(#script), 1, LEN(RTRIM(#script)) - 1)
SELECT #script = #script + ' FROM #TempColumns'
EXEC (#script)
IF OBJECT_ID( 'tempdb..#TempColumns') IS NOT NULL
BEGIN
DROP TABLE #TempColumns
END
IF OBJECT_ID( 'tempdb..#TempColumnsOrder') IS NOT NULL
BEGIN
DROP TABLE #TempColumnsOrder
END
Thanks for reply, Is there any better way in Dynamic SQL other than what i did?
You can eliminate the unsupported string concatenation you are using, and modernize and simply the code:
DROP TABLE IF EXISTS #TempColumns
DROP TABLE IF EXISTS #TempColumnsOrder
CREATE TABLE #TempColumns
(
ID INT IDENTITY,
FirstName VARCHAR(MAX),
LastName VARCHAR(MAX),
Gender VARCHAR(MAX)
)
INSERT INTO #TempColumns
Values('ABC','DEF','MALE'),('PR','ZA','FEMALE'),('ERT','GFG','MALE')
CREATE TABLE #TempColumnsOrder
(
ID INT IDENTITY,
ColumnName VARCHAR(MAX),
ColumnOrder INT
)
INSERT INTO #TempColumnsOrder
Values('FirstName',3), ('LastName',2), ('Gender',1)
SELECT * FROM #TempColumns
SELECT * FROM #TempColumnsOrder
DECLARE #script VARCHAR(MAX) = concat(
'SELECT ',
(select STRING_AGG(QUOTENAME(ColumnName),', ') WITHIN GROUP (ORDER BY ColumnOrder)
FROM #TempColumnsOrder),
' FROM #TempColumns')
print #script
EXEC (#script)
DROP TABLE IF EXISTS #TempColumns
DROP TABLE IF EXISTS #TempColumnsOrder
SELECT #script = #script + ColumnName + ',' FROM #TempColumnsOrder
ORDER BY ColumnOrder
The behavior of aggregate string concatenation with the above technique is not guaranteed. The actual behavior is plan-dependent so you may not get the desired results.
In SQL Server 2017 and Azure SQL Database, STRING_AGG is the proper method:
SELECT STRING_AGG(ColumnName, ',') WITHIN GROUP(ORDER BY ColumnOrder)
FROM #TempColumnsOrder;
In older SQL Versions like SQL Server 2012, the best method is with XML PATH():
SELECT #script = #script +
STUFF((SELECT ',' + ColumnName
FROM #TempColumnsOrder
ORDER BY ColumnOrder
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'');
See this answer for details about how the above query works.
I have a temp table which has a TableName column. I would like to loop through the temporary table and select everything in the the table (where table is the TableName column in the temp table).
I have been looking through the following link and related links however I am unable to adapt it to my needs. Any help is greatly appreciated.
I am using SQL Server 2014
Something which i have tried
Declare #id int
WHILE EXISTS(SELECT * FROM ##tt_tableList)
BEGIN
Select Top 1 #id = Id from ##tt_tableList
-- Do the work --
declare #query nvarchar(max)
set #query = 'Select * from (select TableName from ##tt_tablelist where id = '' +Cast(#id as nvarchar(50))+'')'
select #query
declare #tableName nvarchar(50)
set #tableName = (select TableName from ##tt_tableList where id = #id)
select #tableName
execute(#query)
-- Scrap the ID and Move On --
Delete ##tt_tableList where ID = #id
END
If I understood you correctly this is what you are asking for:
DECLARE #tbl table (TableName varchar(50))
insert into #tbl values ('SomeTableName')
insert into #tbl values ('AnotherTableName')
DECLARE #Tables VARCHAR(8000)
SELECT #Tables = COALESCE(#Tables + CHAR(13), '') + 'SELECT * FROM '+ TableName
FROM #tbl
exec(#Tables)
Just insert your table names in #tbl
I tried this based on answer from one of our fellow stack overflower and it works.
DECLARE #Tables VARCHAR(8000)
SELECT #Tables = COALESCE(#Tables + CHAR(13), '') + 'SELECT * FROM '+ TableName + ' Where Event like ''%CM_Manual_Change%'''
FROM ##tt_tableList
select #Tables
exec(#Tables)
I want to run:
select Mycalculatefunction('((3*4)-3)*5')
select ('((3*4)-3)*5')
OUTPUT: ((3*4)-3)*5 wrong (not int value)
My desired output is: 45
I defined a stored procedure:
create PROCEDURE dbo.Eval
(#exp varchar(MAX))
AS
SET NOCOUNT ON
DECLARE #SQLString NVARCHAR(MAX)
SET #SQLString = 'SELECT '+#exp
EXEC sp_executesql #SQLString
I call it:
exec dbo.Eval '((3*4)-3)*5'
How can I do in this process is the trigger?
Your SP is vulnerable to injection. F.e. I pass exec dbo.Eval '1;DROP TABLE some_table;'. Better use xml.query:
CREATE PROCEDURE dbo.Eval
#formula nvarchar(max)
AS
DECLARE #sql nvarchar(max)
SELECT #sql = N'
DECLARE #x xml = ''''
SELECT CAST(#x.query('''+#formula+''') as nvarchar(max))'
EXEC sp_executesql #sql
Then
EXEC dbo.Eval '((3*4)-3)*5'
Output:
45
Triggers part (as there were no info about your tables, just general explanation, I add full batch with comments):
--Create table that will store Formulas
CREATE TABLE Formulas (
ID int IDENTITY(1,1) NOT NULL,
Formula nvarchar(max) NULL,
CONSTRAINT PK_ID PRIMARY KEY (ID)
)
GO
--Create table to store results of the formulas
CREATE TABLE Results (
T1_ID int NOT NULL,
Result int NULL
)
GO
--Linked by ID
ALTER TABLE Results ADD CONSTRAINT FK_Formulas_Results FOREIGN KEY (T1_ID)
REFERENCES Formulas (ID)
GO
--Create a Table Valued Parameter
CREATE TYPE FormulaResults AS TABLE (
ID int NOT NULL,
Formula nvarchar(max) NULL
)
GO
--Create a procedure to do the count
CREATE PROCEDURE dbo.GetResults
#TVP FormulaResults READONLY
AS
DECLARE #sql nvarchar(max)
SELECT #sql = N'DECLARE #x xml = '''' '
SELECT #sql = #sql + 'SELECT '+CAST(ID as nvarchar(max))+' as ID, CAST(#x.query('''+Formula+''') as nvarchar(max)) UNION ALL '
FROM #TVP
SELECT #sql = LEFT(#sql,LEN(#sql)-LEN('UNION ALL '))
EXEC sp_executesql #sql
GO
--Create a trigger that will count formula after insert and update
CREATE TRIGGER GetResultsTrigger
ON Formulas
AFTER INSERT, UPDATE
AS
DECLARE #FormulaTVP AS FormulaResults
DECLARE #Results TABLE(
T1_ID int NOT NULL,
Result int NULL
)
INSERT INTO #FormulaTVP
SELECT *
FROM inserted
INSERT INTO #Results
EXEC dbo.GetResults #FormulaTVP
MERGE Results r
USING #Results s
ON r.T1_ID = s.T1_ID
WHEN NOT MATCHED THEN
INSERT VALUES (s.T1_ID, s.Result)
WHEN MATCHED THEN
UPDATE SET Result = s.Result;
After that run:
INSERT INTO [Formulas] VALUES
('1+3'),('2+2*8')
SELECT [ID],
[Formula]
FROM [Test].[dbo].[Formulas]
SELECT [T1_ID],
[Result]
FROM [Test].[dbo].[Results]
Output:
ID Formula
1 1+3
2 2+2*8
T1_ID Result
1 4
2 18
image 1
ALTER FUNCTION [dbo].[Calculate]
( #expression AS VARCHAR(MAX)
)
RETURNS xml
AS
BEGIN
-- routine body goes here, e.g.
-- SELECT 'Navicat for SQL Server'
DECLARE #result xml
declare #x xml=''
--I can not pass as a parameter
select #result=#x.query(('(4*3)*5-10'))
return #result;
END
i call this function:
SELECT CAST(CAST(CAST(dbo.[Calculate]('How do I pass parameters') AS XML) AS VARCHAR(100)) AS DECIMAL(4,2))
Output:
50.00
select #result=#x.query('sql:variable("#expression")')
result: '2+2' :(((