问:
column-wise correlation between all pairs of columns of two data frame
Hi so I have created a function to check the correlation between 2 variables, anyone knows how can I create a new data frame from this?

```<code>In [1]:from scipy.stats import pearsonr
for colY in Y.columns:
    for colX in X.columns:
    #print('Pearson Correlation')
        corr, _ = pearsonr(numerical_cols_target[colX], numerical_cols_target[colY])
        alpha = 0.05
        print('Pearson Correlation', (alpha, corr))
        if corr <= alpha:
            print(colX +' and ' +colY+ ' two ariables are not correlated ')
        else:
            print(colX +' and ' +colY+ ' two variables are highly correlated ')
        print('\n')
    print('\n')
</code>```

here's a sample output from the correlation function:

```<code>Out [1]:
Pearson Correlation (0.05, -0.1620045985125294)
banana and orange are not correlated

Pearson Correlation (0.05, 0.2267582070839226)
apple and orange are highly correlated
```
```

答:
I think you are looking for this:
This will get a column-wise correlation of every two pairs of columns between X and Y dataframes and create another dataframe that keeps all the correlations and whether they pass a threshold alpha:
This assumes Y has less or equal number of columns as X. If not simply switch X and Y places:

```<code>import collections
corr_df = pd.DataFrame(columns=['col_X', 'col_Y', 'corr', 'is_correlated'])
d = collections.deque(X.columns)
Y_cols = Y.columns
alpha = 0.05
for i in range(len(d)):
  d.rotate(i)
  X = X[d]
  corr = Y.corrwith(X, axis=0)
  corr_df = corr_df.append(pd.DataFrame({'col_X':list(d)[:len(Y_cols)], 'col_Y':Y.columns, 'corr':corr[:len(Y_cols)], 'is_correlated':corr[:len(Y_cols)]>alpha}))
print(corr_df.reset_index())
</code>```

sample input and output:

```<code>X:
   A  B   C
0  2  2  10
1  4  0   2
2  8  0   1
3  0  0   8

Y:
   B   C
0  2  10
1  0   2
2  0   1
3  0   8

correlation(X, Y):

  col_X col_Y  corr is_correlated
0     A     B   1.0          True
1     B     C   1.0          True
2     C     B   1.0          True
3     A     C   1.0          True
4     A     B   1.0          True
5     B     C   1.0          True
</code>```

Body:
Hi so I have created a function to check the correlation between 2 variables, anyone knows how can I create a new data frame from this?

In [1]:from scipy.stats import pearsonr
for colY in Y.columns:
    for colX in X.columns:
    #print('Pearson Correlation')
        corr, _ = pearsonr(numerical_cols_target[colX], numerical_cols_target[colY])
        alpha = 0.05
        print('Pearson Correlation', (alpha, corr))
        if corr <= alpha:
            print(colX +' and ' +colY+ ' two ariables are not correlated ')
        else:
            print(colX +' and ' +colY+ ' two variables are highly correlated ')
        print('\n')
    print('\n')

here's a sample output from the correlation function:

Out [1]:
Pearson Correlation (0.05, -0.1620045985125294)
banana and orange are not correlated

Pearson Correlation (0.05, 0.2267582070839226)
apple and orange are highly correlated
```

Body:
I think you are looking for this:
This will get a column-wise correlation of every two pairs of columns between X and Y dataframes and create another dataframe that keeps all the correlations and whether they pass a threshold alpha:
This assumes Y has less or equal number of columns as X. If not simply switch X and Y places:

import collections
corr_df = pd.DataFrame(columns=['col_X', 'col_Y', 'corr', 'is_correlated'])
d = collections.deque(X.columns)
Y_cols = Y.columns
alpha = 0.05
for i in range(len(d)):
  d.rotate(i)
  X = X[d]
  corr = Y.corrwith(X, axis=0)
  corr_df = corr_df.append(pd.DataFrame({'col_X':list(d)[:len(Y_cols)], 'col_Y':Y.columns, 'corr':corr[:len(Y_cols)], 'is_correlated':corr[:len(Y_cols)]>alpha}))
print(corr_df.reset_index())

sample input and output:

X:
   A  B   C
0  2  2  10
1  4  0   2
2  8  0   1
3  0  0   8

Y:
   B   C
0  2  10
1  0   2
2  0   1
3  0   8

correlation(X, Y):

  col_X col_Y  corr is_correlated
0     A     B   1.0          True
1     B     C   1.0          True
2     C     B   1.0          True
3     A     C   1.0          True
4     A     B   1.0          True
5     B     C   1.0          True


来源: stackexchange

问:
Initialise logging config from conf file in Python
I want to initialise the logging config using a config file(json or yaml) only once when I call my main module.
Is there a concept of context in python like we have in Java where I can take the logger from config whenever I need.

Something like this in the main module -

```<code>logging.config.fileConfig('log-conf.json')
</code>```

I want to use the loaded config in my entire application without having to load the config in each module.

Also, should I do log = logging.getLogger(__name__) at module level or method level. What is the advantage of doing at method level.

答:
This blog post of mine contains major answers to your question (YAML).

http://glenfant.github.io/the-zen-of-logging-and-yaml.html

You might also have inspiration from this recipe, if you prefer a pure Python config file.

http://glenfant.github.io/simple-customizable-configuration.html

ContentLicense: CC BY-SA 4.0

Body:
I want to initialise the logging config using a config file(json or yaml) only once when I call my main module.
Is there a concept of context in python like we have in Java where I can take the logger from config whenever I need.

Something like this in the main module -

logging.config.fileConfig('log-conf.json')

I want to use the loaded config in my entire application without having to load the config in each module.

Also, should I do log = logging.getLogger(__name__) at module level or method level. What is the advantage of doing at method level.


问:
Ionic 4 - chrome sockets udp not creating socket without outputting any error
I'm trying to use chrome.sockets.udp to send and receive udp packets.
I'm using the following code:

```<code>async broadcasting(messageSend)
{
    var str2ab=function(str) {
        var buf=new ArrayBuffer(str.length);
        var bufView=new Uint8Array(buf);
        for (var i=0; i<str.length; i++) {
        bufView[i]=str.charCodeAt(i);
        }
        return buf;
    }

    // From https://developer.chrome.com/trunk/apps/app_hardware.html
    var ab2str=function(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    };

    var socketId;
    var onReceive = function(info) {
        console.log(info.data);
        if (info.socketId !== socketId)
        return;

    };
    console.log("Creaste");
    var socketOption = {
        persistent: true,
        name: 'udpSocket',
        bufferSize: 4096
    };
    chrome.sockets.udp.onReceiveError.addListener((data) => {
        console.log('received error');
        console.log(data);
    });

    chrome.sockets.udp.onReceive.addListener((data) => {
        console.log('received');
        console.log(data);
    });

    chrome.sockets.udp.create(socketOption, function(socketInfo) {
        socketId = socketInfo.socketId;
        // Setup event handler and bind socket.
       console.log("socketId",socketId);
       alert();

       chrome.sockets.udp.onReceive.addListener(onReceive);
        chrome.sockets.udp.bind(socketId,
            "0.0.0.0", 0, function(result) {
                console.log(" binding socket.");
            if (result < 0) {
                console.log("Erro binding socket.");
                return;
            }//52.20.16.20 40000j
            chrome.sockets.udp.send(socketId, str2ab(ab2str(messageSend)),
            '192.168.1.69', 63580, function(sendInfo) {
                console.log("sent " + sendInfo.bytesSent);
            });
        });

    });
}
</code>```

But the callback of create is never called and in the console i dont get any error or any indication of why the socket is not created! I'm running it on a real android device.
Any idea ?

答: The problem was due to a conflict with another package, I didn't find which one, but by starting a new project and installing only the packages that I needed it started working as supposed.</p>

Body:
I'm trying to use chrome.sockets.udp to send and receive udp packets.
I'm using the following code:

async broadcasting(messageSend)
{
    var str2ab=function(str) {
        var buf=new ArrayBuffer(str.length);
        var bufView=new Uint8Array(buf);
        for (var i=0; i<str.length; i++) {
        bufView[i]=str.charCodeAt(i);
        }
        return buf;
    }

    // From https://developer.chrome.com/trunk/apps/app_hardware.html
    var ab2str=function(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    };

    var socketId;
    var onReceive = function(info) {
        console.log(info.data);
        if (info.socketId !== socketId)
        return;

    };
    console.log("Creaste");
    var socketOption = {
        persistent: true,
        name: 'udpSocket',
        bufferSize: 4096
    };
    chrome.sockets.udp.onReceiveError.addListener((data) => {
        console.log('received error');
        console.log(data);
    });

    chrome.sockets.udp.onReceive.addListener((data) => {
        console.log('received');
        console.log(data);
    });

    chrome.sockets.udp.create(socketOption, function(socketInfo) {
        socketId = socketInfo.socketId;
        // Setup event handler and bind socket.
       console.log("socketId",socketId);
       alert();

       chrome.sockets.udp.onReceive.addListener(onReceive);
        chrome.sockets.udp.bind(socketId,
            "0.0.0.0", 0, function(result) {
                console.log(" binding socket.");
            if (result < 0) {
                console.log("Erro binding socket.");
                return;
            }//52.20.16.20 40000j
            chrome.sockets.udp.send(socketId, str2ab(ab2str(messageSend)),
            '192.168.1.69', 63580, function(sendInfo) {
                console.log("sent " + sendInfo.bytesSent);
            });
        });

    });
}

But the callback of create is never called and in the console i dont get any error or any indication of why the socket is not created! I'm running it on a real android device.
Any idea ?


问:
kdb Interprocess communication and forcing a process to hang
I was wondering if I have 2 kdb processes A and B, and I perform a synchronous call from A like so:

```<code>h(`function_defined_on_b; args);
</code>```

A will hang until function_defined_on_b is executed. But what if function_defined_on_b requires a call to A? I assume it will fail to execute then as the call to A will timeout due to the fact that A is currently hanging. I know making an asynchronous call from A to B would fix this issue, but what should I do in the case where I don't want A to proceed with the code its running until this call is complete?

Alternatively is there any way to stop A from executing whatever code follows the synchronous call but allow it to execute incoming queries from other processes?

Thanks

答:
There isn't really a way to do what you describe. A possible solution would be to have some kind of gateway/aggregator process to run functions which require data across multiple processes. Calling it C:</p>

```<code>Function to run on C:

aggFunc:{

  responseFromA:handleToA(`func;args);

  //process A is free at this point to process the call from B.
  //process C can then wait for this response before sending the next part to A
  responseFromB:handleToB(`func;args);

  responseFromA2:handleToA(`func2;args);

  };
</code>```

Body:
I was wondering if I have 2 kdb processes A and B, and I perform a synchronous call from A like so:

h(`function_defined_on_b; args);

A will hang until function_defined_on_b is executed. But what if function_defined_on_b requires a call to A? I assume it will fail to execute then as the call to A will timeout due to the fact that A is currently hanging. I know making an asynchronous call from A to B would fix this issue, but what should I do in the case where I don't want A to proceed with the code its running until this call is complete?

Alternatively is there any way to stop A from executing whatever code follows the synchronous call but allow it to execute incoming queries from other processes?

Thanks

Body:
There isn't really a way to do what you describe. A possible solution would be to have some kind of gateway/aggregator process to run functions which require data across multiple processes. Calling it C:

Function to run on C:

aggFunc:{

  responseFromA:handleToA(`func;args);

  //process A is free at this point to process the call from B.
  //process C can then wait for this response before sending the next part to A
  responseFromB:handleToB(`func;args);

  responseFromA2:handleToA(`func2;args);

  };


问:
Where do scheduled python programs "print"?
If I schedule print "Hello World!"; to run every hour with crontab, where will Hello World! be printed? Is there a log file?
If I do it with Java or C instead of Python, will it make any difference?

Thanks!

答: They will be sent to the email address defined at the top of the crontab, or to the crontab's owner by default. See the crontab(5) man page for more details.

ContentLicense: CC BY-SA 3.0


问:
Align two audios with similar parts
I have two audios tracks, extracted from two videos.

They sound almost equally except for a few differences.

Different duration. E.g. first track is 10min length, and second track is 10.5min length because it's stretched.

First audio has only English voice. Second audio contains English + foreign-language voice, and you can hear both because they're mixed as voiceover. In other words: audio 1 has Music, Noises, English speech; audio 2 has Music, Noises, English speech, Foreign language speech.

First and second tracks can differ by its windows, or gaps.
E.g. first track could be
scene 1, gap 1sec, scene 2, gap 1sec, scene 3,
and second track could be
scene 1, gap 2sec, scene 2, gap 2sec, scene 3.

I wonder if there are any solutions that could align these two tracks.

That's what I've tried so far:

Cubase 10.5. https://www.youtube.com/watch?v=BGXkHdzjzMg It doesn't work if tracks have different voices.

Revoice Pro. Same - doesn't recognize tracks with different voices. Probably doesn't support long audios.

答:
Dynamic Time Warping (DTW) is the canonical algorithm for aligning sequences of data that might have slight differences in length/speed. The Python library librosa has a brief tutorial on using it for music syncronization.

There might also be DTW implementations in some graphical audio editors, but I am not familiar with any.

Title: Align two audios with similar parts


问:
How to declare a global variable in an header file and how he need to be in the c file
i have a serious problem to understand how to declare a global variable in an header file and how he need to be in the c file.

In my .h :
extern struct my_global_variable glob;

and on my .c i add to reference it :
struct my_global_variable glob;

Is it like that ??
Thanks you for your answer and have a good day/night depend :P

答:
Declare and define the global variable only in  1 .c file and use extern to declare the global variable only in the other .c files.

Example with 3 source files: g.h, g1.c and g2.c:

```<code>    /*
     * g.h
     */

    typedef struct my_global_type {
     int my_field;
    } my_global_type;

    void g2();

 /*
 * g1.c
 */

#include <stdio.h>

#include "g.h"

my_global_type my_global_variable;

int main() {

    my_global_variable.my_field = 1;
    printf("in main: my_global_variable.my_field=%d\n", my_global_variable.my_field);
    g2();
    printf("in main: my_global_variable.my_field=%d\n", my_global_variable.my_field);
    return 0;

}

/*
 * g2.c
 */

#include <stdio.h>

#include "g.h"

extern my_global_type my_global_variable;

void g2() {

    printf("in g2.c: my_global_variable.my_field=%d\n", my_global_variable.my_field);
    my_global_variable.my_field = 2;
    printf("in g2.c: my_global_variable.my_field=%d\n", my_global_variable.my_field);

}
</code>```

You compile with:

```<code> gcc -o g g1.c g2.c
</code>```

And execution says:

```<code>./g
in main: my_global_variable.my_field=1
in g2.c: my_global_variable.my_field=1
in g2.c: my_global_variable.my_field=2
in main: my_global_variable.my_field=2
</code>```

Body:
Declare and define the global variable only in  1 .c file and use extern to declare the global variable only in the other .c files.

Example with 3 source files: g.h, g1.c and g2.c:

    /*
     * g.h
     */

    typedef struct my_global_type {
     int my_field;
    } my_global_type;

    void g2();

 /*
 * g1.c
 */

#include <stdio.h>

#include "g.h"

my_global_type my_global_variable;

int main() {

    my_global_variable.my_field = 1;
    printf("in main: my_global_variable.my_field=%d\n", my_global_variable.my_field);
    g2();
    printf("in main: my_global_variable.my_field=%d\n", my_global_variable.my_field);
    return 0;

}

/*
 * g2.c
 */

#include <stdio.h>

#include "g.h"

extern my_global_type my_global_variable;

void g2() {

    printf("in g2.c: my_global_variable.my_field=%d\n", my_global_variable.my_field);
    my_global_variable.my_field = 2;
    printf("in g2.c: my_global_variable.my_field=%d\n", my_global_variable.my_field);

}

You compile with:

 gcc -o g g1.c g2.c

And execution says:

./g
in main: my_global_variable.my_field=1
in g2.c: my_global_variable.my_field=1
in g2.c: my_global_variable.my_field=2
in main: my_global_variable.my_field=2


问:
How to add active class in wordpress to anchor tag
```<code><li>
  <a href="<?php echo site_url('/blog') ?>"
  <?php if(get_post_type()=='post') echo 'class="active"'?>>Blog</a>
</li>
</code>```

I am trying to add active class to different links in navigation but this code gives an error. Can somebody correct the mistake in above-mentioned code?

答:
Include the following jquery code to your footer and your page will work fine

$(".current_page_item a").addClass("active");

Hope this will help you

Body:
  <a href="<?php echo site_url('/blog') ?>"
  <?php if(get_post_type()=='post') echo 'class="active"'?>>Blog

I am trying to add active class to different links in navigation but this code gives an error. Can somebody correct the mistake in above-mentioned code?


问:
Cannot specify constructor arguments in declaration in C Sharp
This is the Question I am trying to solve in C Sharp.

I am getting an error:

Error Expected ; or = (cannot specify constructor arguments in declaration)

Can anyone help me to solve this or guide me to solve this?

```<code>namespace program
{
    public class Integer
    {
        private int intvar;
        public Integer()
        {
            intvar = 0;
        }
        public Integer(int x)
        {
            intvar = x;
        }
        public void display()
        {
            Console.Write(intvar);
            Console.Write("\n");
        }
        public void add(Integer x, Integer y)
        {
            intvar = x.intvar + y.intvar;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Integer a(5),b(45);
            Integer c;
            c.add(a,b);
            c.display();
            Console.ReadLine();
        }
    }
}
</code>```

答:
You cannot create objects like that in C#. Im assuming you come from C++ where this syntax is possible.

In C# you have to create objects using new:

```<code>Integer foo = new Integer(45);
</code>```

Body:
This is the Question I am trying to solve in C Sharp.

I am getting an error:

Error Expected ; or = (cannot specify constructor arguments in declaration)

Can anyone help me to solve this or guide me to solve this?

namespace program
{
    public class Integer
    {
        private int intvar;
        public Integer()
        {
            intvar = 0;
        }
        public Integer(int x)
        {
            intvar = x;
        }
        public void display()
        {
            Console.Write(intvar);
            Console.Write("\n");
        }
        public void add(Integer x, Integer y)
        {
            intvar = x.intvar + y.intvar;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Integer a(5),b(45);
            Integer c;
            c.add(a,b);
            c.display();
            Console.ReadLine();
        }
    }
}

Body:
You cannot create objects like that in C#. Im assuming you come from C++ where this syntax is possible.

In C# you have to create objects using new:

Integer foo = new Integer(45);


问:
Python function to return concatenated string from a list, where the length of the string is more than 2 characters
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

```<code>def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))
</code>```

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

答:
If I understood your requirement correctly, here is a way to do it:

```<code>from itertools import groupby

res = [''.join(g) for k, g in groupby(lst, lambda x: len(x)>1)]
</code>```

So for lst = ["a", "de", "fg", "hijk", "abc"] (your example) you get:

```<code>['a', 'defghijkabc']
</code>```

and for lst = ["a", "de", "fg", "b", "abc"] you get:

```<code>['a', 'defg', 'b', 'abc']
</code>```

Body:
Newbie learning Python here, be nice!!

I have an assignment as part of my course to write simple programs, but there is one I am struggling with. For all elements in a list that have more than 2 characters, should be concatenated. The code itself is working, but it's returning the first string in the list as well as the other strings which are more than 2 characters. It's because of the way I have written the code I know, but I can't figure out a way to exclude the first string. Iteration should be utilised.

My code:

def concatenate(strings):
    start = strings[0]
    for string in strings:
        if len(string) > 2:
            start += string
    return start

print(concatenate(["a", "de", "fg", "hijk", "abc"]))

It's correctly concatenating hijkabc, but it's also including the "a" at the beginning, so the result I'm actually getting is ahijkabc.

What do I need to do?

Thanks!

Body:
If I understood your requirement correctly, here is a way to do it:

from itertools import groupby

res = [''.join(g) for k, g in groupby(lst, lambda x: len(x)>1)]

So for lst = ["a", "de", "fg", "hijk", "abc"] (your example) you get:

['a', 'defghijkabc']

and for lst = ["a", "de", "fg", "b", "abc"] you get:

['a', 'defg', 'b', 'abc']


问:
change form on button click
I have bootstrap4 registration form, I want change it to login form by pressing on login button, but when I press it nothing happens, just white page. I can not see my login form at the same place where reg form was. What is the problem?:

jQuery(document).ready(function($){
      $('.signupForm').hide();
      $(".login").click(function(){
        $('.reg').hide();
        $(".signupForm").show(300);
      });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
 <script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
 <section>
        <div class="container reg">
          <div class="row justify-content-center">
            <div class="col-12 col-md-8 col-lg-8 col-xl-6">
              <div class="row">
                <div class="col text-center">
                  <h1>Register</h1>
                </div>
              </div>
              <div class="row align-items-center mt-4">
                <div class="col">
                  <input type="email" class="form-control" placeholder="Email">
                </div>
              </div>
              <div class="row align-items-center mt-4">
                <div class="col">
                  <input type="password" class="form-control" placeholder="Password">
                </div>
              </div>
              <div class="row justify-content-start mt-4">
                <div class="col">
                  <button class="btn btn-primary mt-4">Register</button>
                  <button class="btn btn-primary mt-4 login">Login</button>
                </div>
              </div>
            </div>
          </div>

    <div class="signupForm">
      <div class="row align-items-center mt-4">
        <div class="col">
          <input type="email" class="form-control" placeholder="Email">
        </div>
      </div>
      <div class="row align-items-center mt-4">
        <div class="col">
          <input type="password" class="form-control" placeholder="Password">
        </div>
      </div>
    </div>
        </div>
      </section></code>```

答:
The problem is that your .signupForm exist inside the .reg that's why it dont show.

So I've moved reg from:

```<code><div class="container reg">
</code>```

Down to:

```<code><div class="row justify-content-center reg">
</code>```

Demo

jQuery(document).ready(function($) {
  $('.signupForm').hide();
  $(".login").click(function() {
    $('.reg').hide();
    $(".signupForm").show(300);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
html:

<section>
  <div class="container">
    <div class="row justify-content-center reg">
      <div class="col-12 col-md-8 col-lg-8 col-xl-6">
        <div class="row">
          <div class="col text-center">
            <h1>Register</h1>
          </div>
        </div>
        <div class="row align-items-center mt-4">
          <div class="col">
            <input type="email" class="form-control" placeholder="Email">
          </div>
        </div>
        <div class="row align-items-center mt-4">
          <div class="col">
            <input type="password" class="form-control" placeholder="Password">
          </div>
        </div>
        <div class="row justify-content-start mt-4">
          <div class="col">
            <button class="btn btn-primary mt-4">Register</button>
            <button class="btn btn-primary mt-4 login">Login</button>
          </div>
        </div>
      </div>
    </div>

    <div class="signupForm">
      <div class="row align-items-center mt-4">
        <div class="col">
          <input type="email" class="form-control" placeholder="Email">
        </div>
      </div>
      <div class="row align-items-center mt-4">
        <div class="col">
          <input type="password" class="form-control" placeholder="Password">
        </div>
      </div>
    </div>
  </div>
</section></code>```

Title: change form on button click

Body:
I have bootstrap4 registration form, I want change it to login form by pressing on login button, but when I press it nothing happens, just white page. I can not see my login form at the same place where reg form was. What is the problem?:

jQuery(document).ready(function($){
      $('.signupForm').hide();
      $(".login").click(function(){
        $('.reg').hide();
        $(".signupForm").show(300);
      });
    });

 <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Register

                  <input type="email" class="form-control" placeholder="Email">

                  <input type="password" class="form-control" placeholder="Password">

                  <button class="btn btn-primary mt-4">Register</button>
                  <button class="btn btn-primary mt-4 login">Login</button>

          <input type="email" class="form-control" placeholder="Email">

          <input type="password" class="form-control" placeholder="Password">

Body:
The problem is that your .signupForm exist inside the .reg that's why it dont show.

So I've moved reg from:

<div class="container reg">

Down to:

<div class="row justify-content-center reg">

Demo

jQuery(document).ready(function($) {
  $('.signupForm').hide();
  $(".login").click(function() {
    $('.reg').hide();
    $(".signupForm").show(300);
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
html:

<section>
  <div class="container">
    <div class="row justify-content-center reg">
      <div class="col-12 col-md-8 col-lg-8 col-xl-6">
        <div class="row">
          <div class="col text-center">
            <h1>Register</h1>
          </div>
        </div>
        <div class="row align-items-center mt-4">
          <div class="col">
            <input type="email" class="form-control" placeholder="Email">
          </div>
        </div>
        <div class="row align-items-center mt-4">
          <div class="col">
            <input type="password" class="form-control" placeholder="Password">
          </div>
        </div>
        <div class="row justify-content-start mt-4">
          <div class="col">
            <button class="btn btn-primary mt-4">Register</button>
            <button class="btn btn-primary mt-4 login">Login</button>
          </div>
        </div>
      </div>
    </div>

    <div class="signupForm">
      <div class="row align-items-center mt-4">
        <div class="col">
          <input type="email" class="form-control" placeholder="Email">
        </div>
      </div>
      <div class="row align-items-center mt-4">
        <div class="col">
          <input type="password" class="form-control" placeholder="Password">
        </div>
      </div>
    </div>
  </div>
</section>


问:
Why does mysql_query() return TRUE with a SELECT statement?
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

```<code>if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}
</code>```

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

答:
When you say it "returns TRUE," how are you testing that?  You're not by any chance doing something like this, are you?

```<code>$result = mysql_query($sql);
if ($result == TRUE) { /* stuff */ }
</code>```

If so, keep in mind that all non-zero, non-blank, non-null value that is returned will evaluate to TRUE.  You can verify this by using the more stringent:

```<code>if ($result === TRUE) { /* stuff */ }
</code>```

That evaluates not just equivalence, but type as well.  Are you doing something like a var_export($result); to check the data type and verify that you're actually getting back the boolean value of TRUE?

Body:
According to the manual of mysql_query() and to everything I know about this function that I used so many times, it can either return a resource or FALSE if the query is a SELECT. Yet it returns TRUE from time to time.

How can this be? It never ever happened before. Is this a bug in PHP 5.3.2? Does anyone know anything about this?

The code is something like:

if (!$resource = mysql_query($query, $handle)) {
    throw some exception;
}

var_dump($query);
if ($resource === true && strpos($query, 'SELECT') !== false) {
    throw new Exception('mysql_query() returned TRUE for SELECT');
}

It's pretty hard to reproduce, too. It happens only from time to time. I also noticed that it's likely this happens at the same time the server interrupts the connection suddenly, in which case it should return FALSE...

Body:
When you say it "returns TRUE," how are you testing that?  You're not by any chance doing something like this, are you?

$result = mysql_query($sql);
if ($result == TRUE) { /* stuff */ }

If so, keep in mind that all non-zero, non-blank, non-null value that is returned will evaluate to TRUE.  You can verify this by using the more stringent:

if ($result === TRUE) { /* stuff */ }

That evaluates not just equivalence, but type as well.  Are you doing something like a var_export($result); to check the data type and verify that you're actually getting back the boolean value of TRUE?


问:
What is the best way to auto-generate INSERT statements for a SQL Server table?
We are writing a new application, and while testing, we will need a bunch of dummy data. I've added that data by using MS Access to dump excel files into the relevant tables.

Every so often, we want to "refresh" the relevant tables, which means dropping them all, re-creating them, and running a saved MS Access append query.

The first part (dropping & re-creating) is an easy sql script, but the last part makes me cringe. I want a single setup script that has a bunch of INSERTs to regenerate the dummy data.

I have the data in the tables now. What is the best way to automatically generate a big list of INSERT statements from that dataset?

The only way I can think of doing it is to save the table to an excel sheet and then write an excel formula to create an INSERT for every row, which is surely not the best way.

I'm using the 2008 Management Studio to connect to a SQL Server 2005 database.

答:
There are many good scripts above for generating insert statements, but I attempted one of my own to make it as user friendly as possible and to also be able to do UPDATE statements. + package the result ready for .sql files that can be stored by date.

It takes as input your normal SELECT statement with WHERE clause, then outputs a list of Insert statements and update statements. Together they form a sort of IF NOT EXISTS () INSERT ELSE UPDATE It is handy too when there are non-updatable columns that need exclusion from the final INSERT/UPDATE statement.

Another thing that below script can do is: it can even handle INNER JOINs with other tables as input statement for the stored proc. It can be handy as a poor man's Release management tool that sits right at your finger tips where you are typing the sql SELECT statements all day.

original post : Generate UPDATE statement in SQL Server for specific table

```CREATE PROCEDURE [dbo].[sp_generate_updates] (
    @fullquery              nvarchar(max) = '',
    @ignore_field_input     nvarchar(MAX) = '',
    @PK_COLUMN_NAME         nvarchar(MAX) = ''
)
AS

SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1''  '
        OR
                SET QUOTED_IDENTIFIER OFF
                EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1'    "

-- For ignoring specific columns  (to ignore in the UPDATE and INSERT SQL statement)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  ' , 'Column01,Column02'

-- For just updates without insert statement (replace the * )
                EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1  '

-- For tables without a primary key: construct the key in the third variable
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  '  ,'','your_chosen_primary_key_Col1,key_Col2'

-- For complex updates with JOINED tables
                EXEC [sp_generate_updates] 'select o1.Name,  o1.category, o2.name+ '_hello_world' as #name
                                            from overnightsetting o1
                                            inner join overnightsetting o2  on o1.name=o2.name
                                            where o1.name like '%appserver%'
                (REMARK about above:   the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )

-------------README for the deeper interested person:
            Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
            Its power sits also in the fact that you can make insert statements, so combined gives you a  "IF NOT EXISTS()  INSERT "   capability.

            The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
            It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
            The script works with a real  temporary table, made on the fly   (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" ,  and the 2 update statement.
            We work with temporary structures like   "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
                    example  "where columnname = {Columnname}"  for birthdate becomes   "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
            So then the statement becomes  "where birthdate = {19800417}"
            Enjoy releasing scripts as of now...                                        by  Pieter van Nederkassel  - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL     DROP TABLE #ignore
DECLARE @stringsplit_table               TABLE (col nvarchar(255), dtype  nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition                    nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
        @pkstring                        NVARCHAR(512),  -- sting to store the primary keys or the idendity key
        @table_name                      nvarchar(512), -- (left) table name, including schema
        @table_N_where_clause            nvarchar(max), -- tablename
        @table_alias                     nvarchar(512), -- holds the (left) table alias if one available, else @table_name
        @table_schema                    NVARCHAR(30),  -- schema of @table_name
        @update_list1                    NVARCHAR(MAX), -- placeholder for SET fields section of update
        @update_list2                    NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
        @list_all_cols                   BIT = 0,       -- placeholder for values for the insert into table VALUES command
        @select_list                     NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
        @COLUMN_NAME                     NVARCHAR(255), -- will hold column names of the (left) table
        @sql                             NVARCHAR(MAX), -- sql statement variable
        @getdate                         NVARCHAR(17),  -- transform getdate() to YYYYMMDDHHMMSSMMM
        @tmp_table                       NVARCHAR(255), -- will hold the name of a physical temp table
        @pk_separator                    NVARCHAR(1),   -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
        @COLUMN_NAME_DATA_TYPE           NVARCHAR(100), -- needed for insert statements to convert to right text string
        @own_pk                          BIT = 0        -- check if table has PK (0) or if provided PK will be used (1)

set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME=    replace(replace(replace(@PK_COLUMN_NAME,    ' ',''),'[',''),']','')

-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),'  ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
    print ' WARNING:        ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
    select ' WARNING:        IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
    set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
    exec (@table_N_where_clause)

set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)

IF CHARINDEX('where ', @table_N_where_clause) > 0             SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ',  @table_alias) > 0                      SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0                                      SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 )     set @list_all_cols=1
/*
       print @fullquery
       print @table_alias
       print @table_N_where_clause
       print @table_name
*/

-- Prepare PK condition
        SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END

        SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
        AND TABLE_SCHEMA = @table_schema

        SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
        AND i1.TABLE_SCHEMA = @table_schema

            -- if no primary keys exist then we try for identity columns
                IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
                AND TABLE_SCHEMA = @table_schema

                IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
                AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table

        INSERT INTO @stringsplit_table
        SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        inner join INFORMATION_SCHEMA.COLUMNS i2
        on  i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA =  i2.TABLE_SCHEMA
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
        AND i1.TABLE_SCHEMA = @table_schema

                -- if no primary keys exist then we try for identity columns
                IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
                SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
                FROM INFORMATION_SCHEMA.COLUMNS i2
                WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1
                AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
                AND i2.TABLE_SCHEMA = @table_schema

-- NOW handling the primary key given as parameter to the main batch

SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
    IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = ';'
    ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '|'
    ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '-'

    SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
    INSERT INTO @stringsplit_table
    SELECT LTRIM(RTRIM(x.value)) , 'datetime'  FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x
    SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
      FROM @stringsplit_table x

    SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
    SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
      FROM @stringsplit_table x
    --print 'pkcolumns  '+ isnull(@PK_COLUMN_NAME,'')
    update @stringsplit_table set col='pk_' + col
    SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
    RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove  [] from tablename',17,1)
END

-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key

if isnull(@pkstring,'')   = ''  set    @pkstring  = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> ''  SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring

-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement,  in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT           ignore_field = 'uniqueidXXXX' INTO #ignore
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM  string_split(@ignore_field_input,@pk_separator)

SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','')

SET @sql = replace( @fullquery,  ' from ',  ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)

SELECT @sql = N'alter table ' + @tmp_table + N'  add update_stmt1  nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)

-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') +
                      CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
                           WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
                           ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
                      END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')  AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','')
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
                 WHERE 1 = 1
                   AND ku.TABLE_NAME = c2.TABLE_NAME
                   AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
                   AND ku.COLUMN_NAME = c2.COLUMN_NAME
                   AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)

-- Prepare update field list  (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') +  QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'

-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1  -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here

SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+  REPLACE(@table_name,@table_schema+'.','') +'  where '+  @PK_condition +')  INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','')   + '('+ @select_list  + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + ''''
if @list_all_cols=1 EXEC (@sql)

--print 'select==========  ' + @select_list
--print 'update==========  ' + @update_list1

SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
                                          N' SET ' + @update_list1 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') '

EXEC (@sql)
--print @sql

SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
                                          N' SET ' + @update_list2 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') '

EXEC (@sql)
--print @sql

-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME, DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
    AND TABLE_SCHEMA = @table_schema
        UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql =
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
    ELSE
                  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
    END
    ----PRINT @sql
    EXEC (@sql)
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

--SELECT col FROM @stringsplit_table -- these are the primary keys

-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME,DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME =  @tmp_table --    AND TABLE_SCHEMA = @table_schema
       UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql =
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL''))  '
    ELSE
                  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
    END
    EXEC (@sql)
    ----print @sql
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

SET @sql = 'Select * from  ' + @tmp_table + ';'
--exec (@sql)

SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
       SELECT   ''USE ' + DB_NAME()  + '''  as executelist
              UNION ALL
       SELECT   ''GO ''  as executelist
              UNION ALL
       SELECT   '' /*PRESCRIPT CHECK  */              ' + replace(@fullquery,'''','''''')+''' as executelist
              UNION ALL
       SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
              UNION ALL
       SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
              UNION ALL
       SELECT isnull(update_stmt3, '' add more columns inn query please'')  as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
              UNION ALL
       SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 ''  as executelist
              UNION ALL
       SELECT   '' /*VERIFY WITH:  */              ' + replace(@fullquery,'''','''''')+''' as executelist
              UNION ALL
       SELECT ''-- SCRIPT LOCATION:      F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql''  as executelist
END'
exec (@sql)

SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)
```

Body:
There are many good scripts above for generating insert statements, but I attempted one of my own to make it as user friendly as possible and to also be able to do UPDATE statements. + package the result ready for .sql files that can be stored by date.

It takes as input your normal SELECT statement with WHERE clause, then outputs a list of Insert statements and update statements. Together they form a sort of IF NOT EXISTS () INSERT ELSE UPDATE It is handy too when there are non-updatable columns that need exclusion from the final INSERT/UPDATE statement.

Another thing that below script can do is: it can even handle INNER JOINs with other tables as input statement for the stored proc. It can be handy as a poor man's Release management tool that sits right at your finger tips where you are typing the sql SELECT statements all day.

original post : Generate UPDATE statement in SQL Server for specific table

CREATE PROCEDURE [dbo].[sp_generate_updates] (
    @fullquery              nvarchar(max) = '',
    @ignore_field_input     nvarchar(MAX) = '',
    @PK_COLUMN_NAME         nvarchar(MAX) = ''
)
AS

SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1''  '
        OR
                SET QUOTED_IDENTIFIER OFF
                EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1'    "

-- For ignoring specific columns  (to ignore in the UPDATE and INSERT SQL statement)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  ' , 'Column01,Column02'

-- For just updates without insert statement (replace the * )
                EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1  '

-- For tables without a primary key: construct the key in the third variable
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  '  ,'','your_chosen_primary_key_Col1,key_Col2'

-- For complex updates with JOINED tables
                EXEC [sp_generate_updates] 'select o1.Name,  o1.category, o2.name+ '_hello_world' as #name
                                            from overnightsetting o1
                                            inner join overnightsetting o2  on o1.name=o2.name
                                            where o1.name like '%appserver%'
                (REMARK about above:   the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )

-------------README for the deeper interested person:
            Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
            Its power sits also in the fact that you can make insert statements, so combined gives you a  "IF NOT EXISTS()  INSERT "   capability.

            The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
            It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
            The script works with a real  temporary table, made on the fly   (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" ,  and the 2 update statement.
            We work with temporary structures like   "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
                    example  "where columnname = {Columnname}"  for birthdate becomes   "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
            So then the statement becomes  "where birthdate = {19800417}"
            Enjoy releasing scripts as of now...                                        by  Pieter van Nederkassel  - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL     DROP TABLE #ignore
DECLARE @stringsplit_table               TABLE (col nvarchar(255), dtype  nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition                    nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
        @pkstring                        NVARCHAR(512),  -- sting to store the primary keys or the idendity key
        @table_name                      nvarchar(512), -- (left) table name, including schema
        @table_N_where_clause            nvarchar(max), -- tablename
        @table_alias                     nvarchar(512), -- holds the (left) table alias if one available, else @table_name
        @table_schema                    NVARCHAR(30),  -- schema of @table_name
        @update_list1                    NVARCHAR(MAX), -- placeholder for SET fields section of update
        @update_list2                    NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
        @list_all_cols                   BIT = 0,       -- placeholder for values for the insert into table VALUES command
        @select_list                     NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
        @COLUMN_NAME                     NVARCHAR(255), -- will hold column names of the (left) table
        @sql                             NVARCHAR(MAX), -- sql statement variable
        @getdate                         NVARCHAR(17),  -- transform getdate() to YYYYMMDDHHMMSSMMM
        @tmp_table                       NVARCHAR(255), -- will hold the name of a physical temp table
        @pk_separator                    NVARCHAR(1),   -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
        @COLUMN_NAME_DATA_TYPE           NVARCHAR(100), -- needed for insert statements to convert to right text string
        @own_pk                          BIT = 0        -- check if table has PK (0) or if provided PK will be used (1)

set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME=    replace(replace(replace(@PK_COLUMN_NAME,    ' ',''),'[',''),']','')

-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),'  ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
    print ' WARNING:        ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
    select ' WARNING:        IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
    set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
    exec (@table_N_where_clause)

set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)

IF CHARINDEX('where ', @table_N_where_clause) > 0             SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ',  @table_alias) > 0                      SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0                                      SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 )     set @list_all_cols=1
/*
       print @fullquery
       print @table_alias
       print @table_N_where_clause
       print @table_name
*/

-- Prepare PK condition
        SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END

        SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
        AND TABLE_SCHEMA = @table_schema

        SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
        AND i1.TABLE_SCHEMA = @table_schema

            -- if no primary keys exist then we try for identity columns
                IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
                AND TABLE_SCHEMA = @table_schema

                IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
                AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table

        INSERT INTO @stringsplit_table
        SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        inner join INFORMATION_SCHEMA.COLUMNS i2
        on  i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA =  i2.TABLE_SCHEMA
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
        AND i1.TABLE_SCHEMA = @table_schema

                -- if no primary keys exist then we try for identity columns
                IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
                SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
                FROM INFORMATION_SCHEMA.COLUMNS i2
                WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1
                AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
                AND i2.TABLE_SCHEMA = @table_schema

-- NOW handling the primary key given as parameter to the main batch

SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
    IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = ';'
    ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '|'
    ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '-'

    SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
    INSERT INTO @stringsplit_table
    SELECT LTRIM(RTRIM(x.value)) , 'datetime'  FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x
    SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
      FROM @stringsplit_table x

    SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
    SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
      FROM @stringsplit_table x
    --print 'pkcolumns  '+ isnull(@PK_COLUMN_NAME,'')
    update @stringsplit_table set col='pk_' + col
    SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
    RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove  [] from tablename',17,1)
END

-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key

if isnull(@pkstring,'')   = ''  set    @pkstring  = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> ''  SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring

-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement,  in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT           ignore_field = 'uniqueidXXXX' INTO #ignore
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM  string_split(@ignore_field_input,@pk_separator)

SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','')

SET @sql = replace( @fullquery,  ' from ',  ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)

SELECT @sql = N'alter table ' + @tmp_table + N'  add update_stmt1  nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)

-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') +
                      CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
                           WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
                           ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
                      END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')  AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','')
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
                 WHERE 1 = 1
                   AND ku.TABLE_NAME = c2.TABLE_NAME
                   AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
                   AND ku.COLUMN_NAME = c2.COLUMN_NAME
                   AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)

-- Prepare update field list  (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') +  QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'

-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1  -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here

SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+  REPLACE(@table_name,@table_schema+'.','') +'  where '+  @PK_condition +')  INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','')   + '('+ @select_list  + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + ''''
if @list_all_cols=1 EXEC (@sql)

--print 'select==========  ' + @select_list
--print 'update==========  ' + @update_list1

SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
                                          N' SET ' + @update_list1 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') '

EXEC (@sql)
--print @sql

SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
                                          N' SET ' + @update_list2 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') '

EXEC (@sql)
--print @sql

-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME, DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
    AND TABLE_SCHEMA = @table_schema
        UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql =
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
    ELSE
                  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
    END
    ----PRINT @sql
    EXEC (@sql)
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

--SELECT col FROM @stringsplit_table -- these are the primary keys

-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME,DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME =  @tmp_table --    AND TABLE_SCHEMA = @table_schema
       UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql =
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL''))  '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL''))  '
    ELSE
                  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  '
    END
    EXEC (@sql)
    ----print @sql
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

SET @sql = 'Select * from  ' + @tmp_table + ';'
--exec (@sql)

SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
       SELECT   ''USE ' + DB_NAME()  + '''  as executelist
              UNION ALL
       SELECT   ''GO ''  as executelist
              UNION ALL
       SELECT   '' /*PRESCRIPT CHECK  */              ' + replace(@fullquery,'''','''''')+''' as executelist
              UNION ALL
       SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
              UNION ALL
       SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
              UNION ALL
       SELECT isnull(update_stmt3, '' add more columns inn query please'')  as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
              UNION ALL
       SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 ''  as executelist
              UNION ALL
       SELECT   '' /*VERIFY WITH:  */              ' + replace(@fullquery,'''','''''')+''' as executelist
              UNION ALL
       SELECT ''-- SCRIPT LOCATION:      F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql''  as executelist
END'
exec (@sql)

SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)


问:
Flutter: How to jump to last page dynamically created on a PageView
I have a pageView displaying a list of pages.

Application provides a + button to add a new page at the end of the collection.

I need the pageView to automatically jump to the last page once this new page has been successfully created.

If I try to redisplay the view providing a provider with initialPosition set to last pageView index, it does not work

```<code>PageController(initialPage: 0, keepPage: false);
</code>```

Any implementation idea ?

Using listener (but which listener ?)

Complete code:

```<code>  @override
  Widget build(BuildContext context) {
    if (_userId == null) {
      return Scaffold(body: Center(child: Text("Loading experiences")));
    }
    print('Rebuilding entire view.');
    return Scaffold(
      appBar: new AppBar(
          title: StreamBuilder<ExperiencesInfo>(
              stream: _experiencesInfoStream,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  _selectedExperience = snapshot.data.currentExperience;
                  return Text(snapshot.data.currentExperience.name);
                } else {
                  return Center();
                }
              }),
          ),
      body: new Container(
        padding: new EdgeInsets.only(
          top: 16.0,
        ),
        decoration: new BoxDecoration(color: Colors.yellow),
        child: Column(
          children: <Widget>[
            Expanded(
                child:
                StreamBuilder<List<Experience>>(
                    stream: _userExperiencesStream,
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return  _createExperiencesPagesWidget(snapshot.data);
                      } else {
                        return Center();
                      }
                    })
            ),
            _buildPageIndicator(),
            Padding(
              padding: EdgeInsets.only(bottom: 20.0),
            )
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.add),
          onPressed: () {
            _displayAddMenu();
          }),
    );
  }

_createExperiencesPagesWidget(List<Experience> experiences) {
    print('Creating ExperiencesPagesWidget ${experiences}');
    return PageView.builder(
      physics: new AlwaysScrollableScrollPhysics(),
      controller: _pageController,
      itemCount: experiences.length,
      itemBuilder: (BuildContext context, int index) {
        return ConstrainedBox(
            constraints: const BoxConstraints.expand(),
            child: Column(children: <Widget>[
              _buildMoodIndicator(experiences[index]),
              _buildMoodSelector(),
            ]));
      },
      onPageChanged: (index) {
        if (_actionType == ActionType.none) {
          print('page changed to index: ${index}, updating stream.');
          _experiencesViewModel.experienceIndexSink.add(index);
        } else {
          _actionType = ActionType.none;
        }

      },
    );
</code>```

Page controller is defined as a class property

```<code>PageController _pageController = PageController(initialPage: 0, keepPage: false);
</code>```

答:
I think the question here is how to move programmatically from one page to another page which was added after the widget has been created. In the very beginning, there is only one page. When a user enters information correctly on this page, next button became active and another page is added. User can click next and it should jump or animate to the next page. But this approach does not work if I try to really add pages into an array of widgets shown in PageView. It just does not show the next page even if in fact there are pages. I think the problem here is linked to the fact that controller initializes something when attached to a view. And it does not reinit it even if setState is called.

So my workaround for this situation is to add all the required pages in init. Even if there will be placeholder widgets instead of the required pages. Then I have to programmatically control if swipe action is allowed.

Body:
I have a pageView displaying a list of pages.

Application provides a + button to add a new page at the end of the collection.

I need the pageView to automatically jump to the last page once this new page has been successfully created.

If I try to redisplay the view providing a provider with initialPosition set to last pageView index, it does not work

PageController(initialPage: 0, keepPage: false);

Any implementation idea ?

Using listener (but which listener ?)

Complete code:

  @override
  Widget build(BuildContext context) {
    if (_userId == null) {
      return Scaffold(body: Center(child: Text("Loading experiences")));
    }
    print('Rebuilding entire view.');
    return Scaffold(
      appBar: new AppBar(
          title: StreamBuilder<ExperiencesInfo>(
              stream: _experiencesInfoStream,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  _selectedExperience = snapshot.data.currentExperience;
                  return Text(snapshot.data.currentExperience.name);
                } else {
                  return Center();
                }
              }),
          ),
      body: new Container(
        padding: new EdgeInsets.only(
          top: 16.0,
        ),
        decoration: new BoxDecoration(color: Colors.yellow),
        child: Column(
          children: <Widget>[
            Expanded(
                child:
                StreamBuilder<List<Experience>>(
                    stream: _userExperiencesStream,
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return  _createExperiencesPagesWidget(snapshot.data);
                      } else {
                        return Center();
                      }
                    })
            ),
            _buildPageIndicator(),
            Padding(
              padding: EdgeInsets.only(bottom: 20.0),
            )
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.add),
          onPressed: () {
            _displayAddMenu();
          }),
    );
  }

_createExperiencesPagesWidget(List<Experience> experiences) {
    print('Creating ExperiencesPagesWidget ${experiences}');
    return PageView.builder(
      physics: new AlwaysScrollableScrollPhysics(),
      controller: _pageController,
      itemCount: experiences.length,
      itemBuilder: (BuildContext context, int index) {
        return ConstrainedBox(
            constraints: const BoxConstraints.expand(),
            child: Column(children: <Widget>[
              _buildMoodIndicator(experiences[index]),
              _buildMoodSelector(),
            ]));
      },
      onPageChanged: (index) {
        if (_actionType == ActionType.none) {
          print('page changed to index: ${index}, updating stream.');
          _experiencesViewModel.experienceIndexSink.add(index);
        } else {
          _actionType = ActionType.none;
        }

      },
    );

Page controller is defined as a class property

PageController _pageController = PageController(initialPage: 0, keepPage: false);